我发现我可以通过更改textColor
所包含标签的UITextField
来设置占位符颜色。
[[UILabel appearanceWhenContainedIn:[UITextField class], nil] setTextColor:[UIColor lightGrayColor]];
但这也改变了UITextField
文字颜色。有没有办法将它们与UIAppearance
分开指定?
我尝试使用setValue:forKey:
,但之后我读到我的应用可以因使用KVC而被拒绝。
答案 0 :(得分:0)
以@Synmax答案为基础,我将这一类别归为一类,可用于在UITextField中添加占位符文本颜色:
@interface UITextField (Placeholder)
@property UIColor* placeholderTextColor;
@end
@implementation UITextField (Placeholder)
-(UIColor*)placeholderTextColor {
return [self.attributedPlaceholder attribute:NSForegroundColorAttributeName atIndex:0 effectiveRange:nil];
}
-(void)setPlaceholderTextColor:(UIColor*)placeholderTextColor {
if(self.attributedPlaceholder) {
NSMutableAttributedString* as = [[NSMutableAttributedString alloc] initWithAttributedString:self.attributedPlaceholder];
if(placeholderTextColor) {
[as setAttributes:[NSDictionary dictionaryWithObject:placeholderTextColor forKey:NSForegroundColorAttributeName] range:NSMakeRange(0, self.attributedPlaceholder.length)];
} else {
[as removeAttribute:NSForegroundColorAttributeName range:NSMakeRange(0, self.attributedPlaceholder.length)];
}
self.attributedPlaceholder = as;
} else if(self.placeholder) {
self.attributedPlaceholder = [[NSAttributedString alloc] initWithString:self.placeholder attributes:[NSDictionary dictionaryWithObject:placeholderTextColor forKey:NSForegroundColorAttributeName]];
}
}
@end
然后您可以使用如下外观设置占位符文本颜色...
[UITextField appearance].placeholderTextColor = UIColor.grayColor;