观察效果图
UITextField有以下几种特点:
1.默认占位文字是灰色的
2.当光标点上去时,占位文字变为白色
3.光标是白色的
接下来我们通过不同的方法来解决问题
一.将xib中的UITextField与代码关联
通过NSAttributeString方法来更改占位文字的属性(void)viewDidLoad {[super viewDidLoad];// Do any additional setup after loading the view from its nib.//文字属性NSMutableDictionary *dict = [NSMutableDictionary dictionary];dict[NSForegroundColorAttributeName] = [UIColor grayColor];//带有属性的文字(富文本属性)NSAttributeStringNSAttributedString *attr = [[NSAttributedString alloc] initWithString:@"手机号" attributes:dict];self.phoneField.attributedPlaceholder = attr;}但是这种方法只能做出第一种效果,而且不具有通用性。
//画出占位文字- (void)drawPlaceholderInRect:(CGRect)rect {[self.placeholder drawInRect:CGRectMake(0, 13, self.size.width, 25) withAttributes:@{NSForegroundColorAttributeName : [UIColor grayColor],NSFontAttributeName : [UIFont systemFontOfSize:14]}];}这个方法和上一个方法类似,只能做出第一种效果,但这个具有通用性
(void)initialize {unsigned int count = 0;Ivar *ivars = class_copyIvarList([UITextField class] , &count);for (int i = 0; i < count; i++) {//取出成员变量Ivar ivar = *(ivars + i);//打印成员变量名字DDZLog(@"%s",ivar_getName(ivar));}}利用class_copyIvarList这个C函数,将所有的成员变量打印出来
这样我们就可以直接通过KVC进行属性设置了
- (void)awakeFromNib {//修改占位文字颜色[self setValue:[UIColor grayColor] forKeyPath:@"_placeholderLabel.textColor"]; //设置光标颜色和文字颜色一致self.tintColor = self.textColor;}通过这个方法可以完成所有的效果,既具有通用性也简单
//获得焦点时- (BOOL)becomeFirstResponder {//改变占位文字颜色[self setValue:self.textColor forKeyPath:@"_placeholderLabel.textColor"]; return [super becomeFirstResponder];}//失去焦点时- (BOOL)resignFirstResponder {//改变占位文字颜色[self setValue:[UIColor grayColor] forKeyPath:@"_placeholderLabel.textColor"]; return [super resignFirstResponder];}