昨天在和同事聊天中发现自己一直也没怎么使用过 UITextField的leftView 属性,一直就是知道它,但就是没用过它,特此笔记下。
直接使用的时候:
UIImageView *leftView = [[UIImageView alloc] init];
leftView.backgroundColor = [UIColor orangeColor];
textField.leftView =leftView;
textField.leftViewMode = UITextFieldViewModeAlways;
由于直接使用 leftView 属性,leftView会紧紧贴在输入框的边缘,所以需要写一个继承 TextField的,来改变那个边距设置的。
@implementation YSTextField
// 后来发现没必要这样写啦,直接用会更好
//- (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];
// 这样写,可以更好的匹配 Masonry,同时符合原生
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, //默认显示没有
UITextFieldViewModeWhileEditing, //输入时显示
UITextFieldViewModeUnlessEditing, //不输入时显示
UITextFieldViewModeAlways //一直显示有
};
但是注意在使用 rightView 的时候,clearButton的会被覆盖带掉的哦。
另外编辑的时候,如果发现 placeholder 距离边界有问题的话可加上textRect这块的重写。
//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);
}