改变占位文字和光标颜色(利用runtime)

首先新建一个继承自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的占位文字和光标颜色时,只需要继承这个自己写的类就可以了。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容