兩種實(shí)現(xiàn)方式
- 傳統(tǒng)使用KVC實(shí)現(xiàn)
- iOS6.0之后,有attributedPlaceholder屬性尿贫,可以直接通過它更改
1.KVC實(shí)現(xiàn)
[self.titleTF setValue:[UIColor whiteColor] forKeyPath:@"_placeholderLabel.textColor"];
說明
如何知道keyPath是 _placeholderLabel.textColor电媳? 可以直接斷點(diǎn)查看子view成員變量
2.attributedPlaceholder 設(shè)置
@property(nullable, nonatomic,copy) NSAttributedString *attributedPlaceholder NS_AVAILABLE_IOS(6_0);
//
NSMutableAttributedString *placeholder = [[NSMutableAttributedString alloc]initWithString:holderText];
//
[placeholder addAttribute:NSForegroundColorAttributeName value:[UIColor whiteColor] range:NSMakeRange(0, holderText.length)];
//
[placeholder addAttribute:NSFontAttributeName value:[UIFontboldSystemFontOfSize:16] range:NSMakeRange(0, holderText.length)];
//
self.titleTF.attributedPlaceholder = placeholder;
自己踩得坑
在沒有給textField.placeholder 賦值之前上面兩種方法設(shè)置都是無效的,因?yàn)開placeholderLabel 是nil