简体   繁体   English

快速更改占位符文本颜色

[英]Change placeholder text color on swift

How do I change the placeholder text color of a UITextField through Swift?如何通过 Swift 更改 UITextField 的占位符文本颜色? I can't seem to access the placeholder attribute.我似乎无法访问占位符属性。 Thanks谢谢

You can set the placeholder text using an Attributed string .您可以使用Attributed string设置占位符文本。 Set color to attributes Property.将颜色设置为attributes属性。

   textField.attributedPlaceholder = NSAttributedString(string:"placeholder text",
   attributes:[NSForegroundColorAttributeName: UIColor.yellowColor()])

Swift 5斯威夫特 5

textField.attributedPlaceholder = NSAttributedString(string:"placeholder text", attributes:[NSAttributedString.Key.foregroundColor: UIColor.yellow])

在此处输入图片说明

Click on the + button and add a new runtime attribute: _placeholderLabel.textColor单击 + 按钮并添加一个新的运行时属性:_placeholderLabel.textColor

Run your app.运行您的应用程序。

在 swift 中,您可以使用代码更改占位符颜色,

 name_textField .setValue(UIColor.redColor(), forKeyPath: "_placeholderLabel.textColor")

You can create Subclass of Textfield and can override DrawRect function of textfield.您可以创建 Textfield 的子类,并可以覆盖 textfield 的 DrawRect 功能。 By creating subclass you can set that for every textfields Easily.通过创建子类,您可以轻松地为每个文本字段设置它。

class CustomTextfield :UITextField {
 override func drawRect(rect: CGRect) {
self.attributedPlaceholder = NSAttributedString(string:self.placeholder != nil ? self.placeholder! : "", attributes:[NSForegroundColorAttributeName: UIColor.grayColor()])
} }

斯威夫特 4:

emailTextField.attributedPlaceholder = NSAttributedString(string: "e-mail", attributes: [NSAttributedStringKey.foregroundColor : UIColor.white])

迅捷 5

  text.attributedPlaceholder = NSAttributedString(string: "your holder text", attributes: [NSAttributedString.Key.foregroundColor : textHolderColor])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM