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