我想改变我在UITextField控件中设置的占位符文本的颜色,使其为黑色。

我更喜欢这样做,而不使用普通文本作为占位符,并且不得不重写所有方法来模仿占位符的行为。

我相信如果我重写这个方法:

- (void)drawPlaceholderInRect:(CGRect)rect

那么我就能做这个了。但是我不确定如何从这个方法中访问实际的占位符对象。


当前回答

你可以改变占位符文本颜色的任何颜色,你想通过使用下面的代码。

UIColor *color = [UIColor lightTextColor];
YOURTEXTFIELD.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"PlaceHolder Text" attributes:@{NSForegroundColorAttributeName: color}];

其他回答

我需要保持占位符的对齐,这样亚当的答案对我来说就不够了。

为了解决这个问题,我使用了一个小的变化,我希望也能帮助到你们:

- (void) drawPlaceholderInRect:(CGRect)rect {
    //search field placeholder color
    UIColor* color = [UIColor whiteColor];

    [color setFill];
    [self.placeholder drawInRect:rect withFont:self.font lineBreakMode:UILineBreakModeTailTruncation alignment:self.textAlignment];
}

简单无痛,对一些人来说可能是一个简单的选择。

_placeholderLabel.textColor

不建议制作,Apple可能会拒绝您的提交。

你可以改变占位符文本颜色的任何颜色,你想通过使用下面的代码。

UIColor *color = [UIColor lightTextColor];
YOURTEXTFIELD.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"PlaceHolder Text" attributes:@{NSForegroundColorAttributeName: color}];

也许你想尝试这种方式,但苹果可能会警告你访问私有ivar:

[self.myTextField setValue:[UIColor darkGrayColor] 
                forKeyPath:@"_placeholderLabel.textColor"];

请注意 根据Martin Alléus的说法,iOS 7不再适用了。

你可以重写drawPlaceholderInRect:(CGRect)rect来手动渲染占位符文本:

- (void) drawPlaceholderInRect:(CGRect)rect {
    [[UIColor blueColor] setFill];
    [[self placeholder] drawInRect:rect withFont:[UIFont systemFontOfSize:16]];
}