[_textField setValue:self.placeholderColor forKeyPath:@"_placeholderLabel.textColor"];
如果你的代碼通過 KVC 方式修改私有屬性,有 Crash 風(fēng)險。
解決問題
對UITextField創(chuàng)建一個新的分類,例如:
//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
這樣項目中有多個地方使用就可以很快替換掉。