有没有办法使用UIAppearance设置UITextField的占位符颜色

时间:2014-04-29 19:06:32

标签: ios uitextfield uiappearance

我发现我可以通过更改textColor所包含标签的UITextField来设置占位符颜色。

[[UILabel appearanceWhenContainedIn:[UITextField class], nil] setTextColor:[UIColor lightGrayColor]];

但这也改变了UITextField文字颜色。有没有办法将它们与UIAppearance分开指定?

我尝试使用setValue:forKey:,但之后我读到我的应用可以因使用KVC而被拒绝。

1 个答案:

答案 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;