2023年7月14日发(作者:)
UITextFieldleftViewrightView昨天在和同事聊天中发现⾃⼰⼀直也没怎么使⽤过 UITextField的leftView 属性,⼀直就是知道它,但就是没⽤过它,特此笔记下。leftViewrightView直接使⽤的时候:UIImageView *leftView = [[UIImageView alloc] init];oundColor = [UIColor orangeColor];ew =leftView;ewMode = UITextFieldViewModeAlways;由于直接使⽤ leftView 属性,leftView会紧紧贴在输⼊框的边缘,所以需要写⼀个继承 TextField的,来改变那个边距设置的。@implementation YSTextField// 后来发现没必要这样写啦,直接⽤会更好//- (instancetype)initWithFrame:(CGRect)frame iconLeftView:(UIView *)leftView iconRightView:(UIView *)rightView//{// self = [super initWithFrame:frame];// if (self) {// if (leftView) {// ew = leftView;// ewMode = UITextFieldViewModeAlways;// }// if (rightView) {// iew = rightView;// iewMode = UITextFieldViewModeAlways;// }// }// return self;//}- (CGRect)leftViewRectForBounds:(CGRect)bounds { CGRect leftRect = [super leftViewRectForBounds:bounds]; .x += 10; //右边偏10 return leftRect;}- (CGRect)rightViewRectForBounds:(CGRect)bounds { CGRect rightRect = [super rightViewRectForBounds:bounds]; .x -= 10; //左边偏10 return rightRect;}@end然后直接使⽤就 OK 了UIImageView *leftView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 20, 20)];oundColor = [UIColor redColor];// YSTextField *textField = [[YSTextField alloc] initWithFrame:CGRectZero// iconLeftView:leftView// iconRightView:nil];// 这样写,可以更好的匹配 Masonry,同时符合原⽣YSTextField *textField = [[YSTextField alloc] init];ew = leftView;ewMode = UITextFieldViewModeAlways;older = @"testTextField";Style = UITextBorderStyleRoundedRect;[ addSubview:textField];[textField mas_makeConstraints:^(MASConstraintMaker *make) { o(@100); o(@30); o(@(-30)); o(@40);}];ps: UITextFieldViewModetypedef NS_ENUM(NSInteger, UITextFieldViewMode) { UITextFieldViewModeNever, //默认显⽰没有 UITextFieldViewModeWhileEditing, //输⼊时显⽰ UITextFieldViewModeUnlessEditing, //不输⼊时显⽰ UITextFieldViewModeAlways //⼀直显⽰有};但是注意在使⽤ rightView 的时候,clearButton的会被覆盖带掉的哦。另外编辑的时候,如果发现 placeholder 距离边界有问题的话可加上textRect这块的重写。//UITextField ⽂字与输⼊框的距离- (CGRect)textRectForBounds:(CGRect)bounds{ if (ew) { return CGRectInset(bounds, 40, 0); } return CGRectInset(bounds, 10, 0);
}//控制编辑⽂本的位置- (CGRect)editingRectForBounds:(CGRect)bounds{ if (ew) { return CGRectInset(bounds, 40, 0); } return CGRectInset(bounds, 10, 0);}备注
发布者:admin,转转请注明出处:http://www.yc00.com/web/1689264158a226408.html
评论列表(0条)