首先新建一个继承自UITextFiled的类,在.m文件中导入<objc/runtime.h>,并定义静态的变量储存UITextFiled的内部属性作为Key值。
static NSString * const PlacerholderColorKeyPath = @"_placeholderLabel.textColor";
重写以下方法
- (void)awakeFromNib
{
// UILabel *placeholderLabel = [self valueForKeyPath:@"_placeholderLabel"];
// placeholderLabel.textColor = [UIColor redColor];
// // 修改占位文字颜色,利用kvc改变属性值
// [self setValue:[UIColor grayColor] forKeyPath:@"_placeholderLabel.textColor"];
// 设置光标颜色和文字颜色一致
self.tintColor = self.textColor;
// 不成为第一响应者
[self resignFirstResponder];
}
/**
* 当前文本框聚焦时就会调用
*/
- (BOOL)becomeFirstResponder
{
// 修改占位文字颜色
[self setValue:self.textColor forKeyPath:PlacerholderColorKeyPath];//占位文字颜色和输入的文字颜色一样
return [super becomeFirstResponder];
}
/**
* 当前文本框失去焦点时就会调用
*/
- (BOOL)resignFirstResponder
{
// 修改占位文字颜色
[self setValue:[UIColor grayColor] forKeyPath:PlacerholderColorKeyPath];
return [super resignFirstResponder];
}
在需要用改变texeFiled的占位文字和光标颜色时,只需要继承这个自己写的类就可以了。