我想改变我在UITextField控件中设置的占位符文本的颜色,使其为黑色。
我更喜欢这样做,而不使用普通文本作为占位符,并且不得不重写所有方法来模仿占位符的行为。
我相信如果我重写这个方法:
- (void)drawPlaceholderInRect:(CGRect)rect
那么我就能做这个了。但是我不确定如何从这个方法中访问实际的占位符对象。
我想改变我在UITextField控件中设置的占位符文本的颜色,使其为黑色。
我更喜欢这样做,而不使用普通文本作为占位符,并且不得不重写所有方法来模仿占位符的行为。
我相信如果我重写这个方法:
- (void)drawPlaceholderInRect:(CGRect)rect
那么我就能做这个了。但是我不确定如何从这个方法中访问实际的占位符对象。
当前回答
[txt_field setValue:ColorFromHEX(@"#525252") forKeyPath:@"_placeholderLabel.textColor"];
其他回答
[txt_field setValue:ColorFromHEX(@"#525252") forKeyPath:@"_placeholderLabel.textColor"];
自从ios6在UIViews中引入了带属性字符串,就可以像这样为占位符文本分配颜色:
if ([textField respondsToSelector:@selector(setAttributedPlaceholder:)]) {
UIColor *color = [UIColor blackColor];
textField.attributedPlaceholder = [[NSAttributedString alloc] initWithString:placeholderText attributes:@{NSForegroundColorAttributeName: color}];
} else {
NSLog(@"Cannot set placeholder text's color, because deployment target is earlier than iOS 6.0");
// TODO: Add fall-back code to set placeholder color.
}
iOS 6及后续版本在UITextField上提供attributedPlaceholder。 iOS 3.2及更高版本提供了setAttributes:range: on NSMutableAttributedString。
您可以执行以下操作:
NSMutableAttributedString *ms = [[NSMutableAttributedString alloc] initWithString:self.yourInput.placeholder];
UIFont *placeholderFont = self.yourInput.font;
NSRange fullRange = NSMakeRange(0, ms.length);
NSDictionary *newProps = @{NSForegroundColorAttributeName:[UIColor yourColor], NSFontAttributeName:placeholderFont};
[ms setAttributes:newProps range:fullRange];
self.yourInput.attributedPlaceholder = ms;
简单无痛,对一些人来说可能是一个简单的选择。
_placeholderLabel.textColor
不建议制作,Apple可能会拒绝您的提交。
在swift 3中。X
textField.attributedPlaceholder = NSAttributedString(string: "placeholder text", attributes:[NSForegroundColorAttributeName: UIColor.black])
在swift 5中
textField.attributedPlaceholder = NSAttributedString(string: "placeholder text", attributes: [NSAttributedString.Key.foregroundColor : UIColor.black])