我想改变我在UITextField控件中设置的占位符文本的颜色,使其为黑色。
我更喜欢这样做,而不使用普通文本作为占位符,并且不得不重写所有方法来模仿占位符的行为。
我相信如果我重写这个方法:
- (void)drawPlaceholderInRect:(CGRect)rect
那么我就能做这个了。但是我不确定如何从这个方法中访问实际的占位符对象。
我想改变我在UITextField控件中设置的占位符文本的颜色,使其为黑色。
我更喜欢这样做,而不使用普通文本作为占位符,并且不得不重写所有方法来模仿占位符的行为。
我相信如果我重写这个方法:
- (void)drawPlaceholderInRect:(CGRect)rect
那么我就能做这个了。但是我不确定如何从这个方法中访问实际的占位符对象。
当前回答
对于设置属性文本字段占位符与多种颜色,
只要指定文本,
//txtServiceText is your Textfield
_txtServiceText.placeholder=@"Badal/ Shah";
NSMutableAttributedString *mutable = [[NSMutableAttributedString alloc] initWithString:_txtServiceText.placeholder];
[mutable addAttribute: NSForegroundColorAttributeName value:[UIColor whiteColor] range:[_txtServiceText.placeholder rangeOfString:@"Badal/"]]; //Replace it with your first color Text
[mutable addAttribute: NSForegroundColorAttributeName value:[UIColor orangeColor] range:[_txtServiceText.placeholder rangeOfString:@"Shah"]]; // Replace it with your secondcolor string.
_txtServiceText.attributedPlaceholder=mutable;
输出:
其他回答
我需要保持占位符的对齐,这样亚当的答案对我来说就不够了。
为了解决这个问题,我使用了一个小的变化,我希望也能帮助到你们:
- (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];
}
我已经遇到过这个问题了。在我的情况下,以下代码是正确的。
Objective - C
[textField setValue:[UIColor whiteColor] forKeyPath:@"_placeholderLabel.textColor"];
Swift 4。X
tf_mobile.setValue(UIColor.white, forKeyPath: "_placeholderLabel.textColor")
适用于iOS 13 Swift Code
tf_mobile.attributedPlaceholder = NSAttributedString(string:"PlaceHolder Text", attributes: [NSAttributedString.Key.foregroundColor: UIColor.red])
你也可以在iOS 13中使用下面的代码
let iVar = class_getInstanceVariable(UITextField.self, "_placeholderLabel")!
let placeholderLabel = object_getIvar(tf_mobile, iVar) as! UILabel
placeholderLabel.textColor = .red
霍普,这个也许能帮到你。
简单无痛,对一些人来说可能是一个简单的选择。
_placeholderLabel.textColor
不建议制作,Apple可能会拒绝您的提交。
另一个不需要子类化的选项-留空占位符,并将标签放在编辑按钮的顶部。管理标签就像你会管理占位符(清除一旦用户输入任何东西..)
同样在你的故事板中,没有一行代码