A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© sabjiang 中级黑马   /  2014-5-17 17:25  /  1722 人查看  /  0 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

Insets就是css中的padding

我们给UITextField设置了leftView,目的是在文本输入框左侧显示一个图标。但是在ios7里,这个图标会紧紧地挨着TextField的左边框,很不美观,所以就希望设置一个Insets。但是直接设置ImageView的bounds不行,需要用下面这个方法:
  1. @interface YLSTextField : UITextField

  2. -(id)initWithFrame:(CGRect)frame Icon:(UIImageView*)icon;

  3. @end
复制代码

  1. @implementation YLSTextField

  2. -(id)initWithFrame:(CGRect)frame Icon:(UIImageView*)icon
  3. {
  4.   self = [super initWithFrame:frame];
  5.   if (self) {
  6.     self.leftView = icon;
  7.     self.leftViewMode = UITextFieldViewModeAlways;
  8.   }
  9.   return self;
  10. }

  11. -(CGRect) leftViewRectForBounds:(CGRect)bounds {
  12.   CGRect iconRect = [super leftViewRectForBounds:bounds];
  13.   iconRect.origin.x += 10;// 右偏10
  14.   return iconRect;
  15. }

  16. @end
复制代码
  1. UIImage *usernameImage = [UIImage imageNamed:@"user"];
  2. UIImageView *usernameIcon = [[UIImageView alloc] initWithImage:usernameImage];
  3. usernameIcon.frame = CGRectMake(0, 0, 20, 20);
  4.         
  5. self.username = [[YLSTextField alloc] initWithFrame:CGRectMake(0, 0, 240, 30) Icon:usernameIcon];
  6. self.username.placeholder = @"用户名";
  7. self.username.borderStyle = UITextBorderStyleRoundedRect;
  8. self.username.clearButtonMode = UITextFieldViewModeWhileEditing;
  9. [self.username setKeyboardType:UIKeyboardTypeNumberPad];
复制代码

关键就是定义UITextField的子类,并覆盖其leftViewRectForBounds方法

0 个回复

您需要登录后才可以回帖 登录 | 加入黑马