首页 > 代码库 > UITextField设置leftView的Insets
UITextField设置leftView的Insets
Insets就是css中的padding
我们给UITextField设置了leftView,目的是在文本输入框左侧显示一个图标。但是在ios7里,这个图标会紧紧地挨着TextField的左边框,很不美观,所以就希望设置一个Insets。但是直接设置ImageView的bounds不行,需要用下面这个方法:
@interface YLSTextField : UITextField -(id)initWithFrame:(CGRect)frame Icon:(UIImageView*)icon; @end
@implementation YLSTextField -(id)initWithFrame:(CGRect)frame Icon:(UIImageView*)icon { self = [super initWithFrame:frame]; if (self) { self.leftView = icon; self.leftViewMode = UITextFieldViewModeAlways; } return self; } -(CGRect) leftViewRectForBounds:(CGRect)bounds { CGRect iconRect = [super leftViewRectForBounds:bounds]; iconRect.origin.x += 10;// 右偏10 return iconRect; } @end
UIImage *usernameImage = [UIImage imageNamed:@"user"]; UIImageView *usernameIcon = [[UIImageView alloc] initWithImage:usernameImage]; usernameIcon.frame = CGRectMake(0, 0, 20, 20); self.username = [[YLSTextField alloc] initWithFrame:CGRectMake(0, 0, 240, 30) Icon:usernameIcon]; self.username.placeholder = @"用户名"; self.username.borderStyle = UITextBorderStyleRoundedRect; self.username.clearButtonMode = UITextFieldViewModeWhileEditing; [self.username setKeyboardType:UIKeyboardTypeNumberPad];
关键就是定义UITextField的子类,并覆盖其leftViewRectForBounds方法
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。