我想改变我在UITextField控件中设置的占位符文本的颜色,使其为黑色。
我更喜欢这样做,而不使用普通文本作为占位符,并且不得不重写所有方法来模仿占位符的行为。
我相信如果我重写这个方法:
- (void)drawPlaceholderInRect:(CGRect)rect
那么我就能做这个了。但是我不确定如何从这个方法中访问实际的占位符对象。
我想改变我在UITextField控件中设置的占位符文本的颜色,使其为黑色。
我更喜欢这样做,而不使用普通文本作为占位符,并且不得不重写所有方法来模仿占位符的行为。
我相信如果我重写这个方法:
- (void)drawPlaceholderInRect:(CGRect)rect
那么我就能做这个了。但是我不确定如何从这个方法中访问实际的占位符对象。
当前回答
迅速:
if let placeholder = yourTextField.placeholder {
yourTextField.attributedPlaceholder = NSAttributedString(string:placeholder,
attributes: [NSForegroundColorAttributeName: UIColor.blackColor()])
}
在Swift 4.0中:
if let placeholder = yourTextField.placeholder {
yourTextField.attributedPlaceholder = NSAttributedString(string:placeholder,
attributes: [NSAttributedStringKey.foregroundColor: UIColor.black])
}
其他回答
也许你想尝试这种方式,但苹果可能会警告你访问私有ivar:
[self.myTextField setValue:[UIColor darkGrayColor]
forKeyPath:@"_placeholderLabel.textColor"];
请注意 根据Martin Alléus的说法,iOS 7不再适用了。
对于设置属性文本字段占位符与多种颜色,
只要指定文本,
//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;
输出:
我已经遇到过这个问题了。在我的情况下,以下代码是正确的。
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
霍普,这个也许能帮到你。
自从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中改变文本字段占位符文本的颜色
[self.userNameTxt setValue:[UIColor colorWithRed:41.0/255.0 green:91.0/255.0 blue:106.0/255.0 alpha:1.0] forKeyPath:@"_placeholderLabel.textColor"];