如何动态更改占位符颜色UITextField
?这始终是相同的系统颜色.
xib编辑器中没有选项.
来自Docs
@property(非原子,复制)NSAttributedString*attributedPlaceholder
默认情况下,此属性为零.如果设置,则使用70%灰色和属性字符串的剩余样式信息(文本颜色除外)绘制占位符字符串.为此属性分配新值也会使用相同的字符串数据替换占位符属性的值,尽管没有任何格式设置信息.为此属性指定新值不会影响文本字段的任何其他与样式相关的属性.
Objective-C的
NSAttributedString *str = [[NSAttributedString alloc] initWithString:@"Some Text" attributes:@{ NSForegroundColorAttributeName : [UIColor redColor] }]; self.myTextField.attributedPlaceholder = str;
迅速
let str = NSAttributedString(string: "Text", attributes: [NSForegroundColorAttributeName:UIColor.redColor()]) myTextField.attributedPlaceholder = str
斯威夫特4
let str = NSAttributedString(string: "Text", attributes: [NSAttributedString.Key.foregroundColor: UIColor.red]) myTextField.attributedPlaceholder = str
首先添加此扩展名
extension UITextField{ @IBInspectable var placeHolderTextColor: UIColor? { set { let placeholderText = self.placeholder != nil ? self.placeholder! : "" attributedPlaceholder = NSAttributedString(string:placeholderText, attributes:[NSForegroundColorAttributeName: newValue!]) } get{ return self.placeHolderTextColor } } }
然后,您可以通过故事板更改占位符文本颜色,或者只需将其设置为:
textfield.placeHolderTextColor = UIColor.red
_placeholderLabel.textColor
在迅速
myTextField.attributedPlaceholder = NSAttributedString(string: "placeholder", attributes:[NSForegroundColorAttributeName : UIColor.redColor()])
Objective-C的
UIColor *color = [UIColor grayColor]; nameText.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"Full Name" attributes:@{NSForegroundColorAttributeName:color}];
PS复制了Stackoverflow的3个不同答案.
使用以下代码
[YourtextField setValue:[UIColor colorWithRed:97.0/255.0 green:1.0/255.0 blue:17.0/255.0 alpha:1.0] forKeyPath:@"_placeholderLabel.textColor"];