美文网首页
UITextField 的私有属性 _placeholderLa

UITextField 的私有属性 _placeholderLa

作者: wingsrao | 来源:发表于2019-10-08 15:27 被阅读0次
[_textField setValue:self.placeholderColor forKeyPath:@"_placeholderLabel.textColor"];
如果你的代码通过 KVC 方式修改私有属性,有 Crash 风险。

解决问题

对UITextField创建一个新的分类,例如:

//h文件
UITextField+Placeholder.h
@interface UITextField (Placeholder)
- (void)setPlaceholderColor:(UIColor *)color;
@end
//下面为m文件
#import "UITextField+Placeholder.h"
#import <objc/runtime.h>

@implementation UITextField (Placeholder)

- (void)setPlaceholderColor:(UIColor *)color{
    Ivar ivar =  class_getInstanceVariable([UITextField class], "_placeholderLabel");
    UILabel *placeholderLabel = object_getIvar(self, ivar);
    placeholderLabel.textColor = color;
}
//使用
[self.textFiled setPlaceholderColor:[UIColor redColor]];

@end

这样项目中有多个地方使用就可以很快替换掉。

相关文章

网友评论

      本文标题:UITextField 的私有属性 _placeholderLa

      本文链接:https://www.haomeiwen.com/subject/hmrmuctx.html