UITextField相关操作

这里介绍一下关于 UITextField 的几个常用的操作,包括定义搜索框样式等

左侧添加图片

UIImageView *img = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"right.png"]];  
text.rightView = img;
text.rightViewMode = UITextFieldViewModeAlways;
text.leftView = img;
text.leftViewMode = UITextFieldViewModeAlways;

设置垂直居中

UITextField 继承自 UIControl,此类中有一个属性contentVerticalAlignment
所以想让UITextField里面的text垂直居中可以这样写:

text.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;

用UITextField自定义UISearchBar样式

定义样式为左侧带放大镜,背景白色,圆角

UITextField *textField = [[UITextField alloc]initWithFrame:CGRectMake(80, 7, 180, 30)];
textField.borderStyle = UITextBorderStyleNone;
textField.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
textField.backgroundColor = [UIColor whiteColor];
textField.placeholder = @"输入要搜索的内容";
textField.font = [UIFont systemFontOfSize:12];
textField.layer.cornerRadius = 3.0;
UIView *leftV = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 30, 30)];
UIImageView *leftImg = [[UIImageView alloc]initWithFrame:CGRectMake(9, 9, 12, 12)];
leftImg.image = [UIImage imageNamed:@"main_search_icon"];//放大镜的图片
[leftV addSubview:leftImg];
textField.leftView = leftV;
textField.leftViewMode = UITextFieldViewModeAlways;

设置内边框

[self.yourTextField setValue:[NSNumber numberWithInt:5] forKey:@"_paddingTop"];
[self.yourTextField setValue:[NSNumber numberWithInt:5] forKey:@"_paddingLeft"];
[self.yourTextField setValue:[NSNumber numberWithInt:5] forKey:@"_paddingBottom"];
[self.yourTextField setValue:[NSNumber numberWithInt:5] forKey:@"_paddingRight"];