昨天在和同事聊天中發(fā)現(xiàn)自己一直也沒(méi)怎么使用過(guò) UITextField的leftView 屬性桶良,一直就是知道它嗜侮,但就是沒(méi)用過(guò)它焊虏,特此筆記下淡喜。
leftView
rightView
直接使用的時(shí)候:
UIImageView *leftView = [[UIImageView alloc] init];
leftView.backgroundColor = [UIColor orangeColor];
textField.leftView =leftView;
textField.leftViewMode = UITextFieldViewModeAlways;
由于直接使用 leftView 屬性,leftView會(huì)緊緊貼在輸入框的邊緣,所以需要寫(xiě)一個(gè)繼承 TextField的诵闭,來(lái)改變那個(gè)邊距設(shè)置的炼团。
@implementation YSTextField
// 后來(lái)發(fā)現(xiàn)沒(méi)必要這樣寫(xiě)啦,直接用會(huì)更好
//- (instancetype)initWithFrame:(CGRect)frame iconLeftView:(UIView *)leftView iconRightView:(UIView *)rightView
//{
// self = [super initWithFrame:frame];
// if (self) {
// if (leftView) {
// self.leftView = leftView;
// self.leftViewMode = UITextFieldViewModeAlways;
// }
// if (rightView) {
// self.rightView = rightView;
// self.rightViewMode = UITextFieldViewModeAlways;
// }
// }
// return self;
//}
- (CGRect)leftViewRectForBounds:(CGRect)bounds {
CGRect leftRect = [super leftViewRectForBounds:bounds];
leftRect.origin.x += 10; //右邊偏10
return leftRect;
}
- (CGRect)rightViewRectForBounds:(CGRect)bounds {
CGRect rightRect = [super rightViewRectForBounds:bounds];
rightRect.origin.x -= 10; //左邊偏10
return rightRect;
}
@end
然后直接使用就 OK 了
UIImageView *leftView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 20, 20)];
leftView.backgroundColor = [UIColor redColor];
// YSTextField *textField = [[YSTextField alloc] initWithFrame:CGRectZero
// iconLeftView:leftView
// iconRightView:nil];
// 這樣寫(xiě)疏尿,可以更好的匹配 Masonry,同時(shí)符合原生
YSTextField *textField = [[YSTextField alloc] init];
textField.leftView = leftView;
textField.leftViewMode = UITextFieldViewModeAlways;
textField.placeholder = @"testTextField";
textField.borderStyle = UITextBorderStyleRoundedRect;
[self.view addSubview:textField];
[textField mas_makeConstraints:^(MASConstraintMaker *make) {
make.top.equalTo(@100);
make.leading.equalTo(@30);
make.trailing.equalTo(@(-30));
make.height.equalTo(@40);
}];
ps: UITextFieldViewMode
typedef NS_ENUM(NSInteger, UITextFieldViewMode) {
UITextFieldViewModeNever, //默認(rèn)顯示沒(méi)有
UITextFieldViewModeWhileEditing, //輸入時(shí)顯示
UITextFieldViewModeUnlessEditing, //不輸入時(shí)顯示
UITextFieldViewModeAlways //一直顯示有
};
但是注意在使用 rightView 的時(shí)候瘟芝,clearButton的會(huì)被覆蓋帶掉的哦。
另外編輯的時(shí)候褥琐,如果發(fā)現(xiàn) placeholder 距離邊界有問(wèn)題的話可加上textRect這塊的重寫(xiě)锌俱。
//UITextField 文字與輸入框的距離
- (CGRect)textRectForBounds:(CGRect)bounds{
if (self.leftView) {
return CGRectInset(bounds, 40, 0);
}
return CGRectInset(bounds, 10, 0);
}
//控制編輯文本的位置
- (CGRect)editingRectForBounds:(CGRect)bounds{
if (self.leftView) {
return CGRectInset(bounds, 40, 0);
}
return CGRectInset(bounds, 10, 0);
}