在Swift中更改占位符文本的颜色

6

我该如何通过Swift更改UITextField的占位符文本颜色?我似乎无法访问占位符属性。谢谢

6个回答

18

您可以使用属性字符串设置占位符文本。将颜色设置为属性属性。

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

Swift 5

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

6

enter image description here

点击 + 按钮并添加一个新的运行时属性: _placeholderLabel.textColor

运行你的应用程序。


3
在Swift中,您可以使用以下代码更改placeholderColor:
 name_textField .setValue(UIColor.redColor(), forKeyPath: "_placeholderLabel.textColor")

这不是一个好的解决方案。使用这种方法,您不能保证应用商店的批准,并且它可能在未来的iOS版本中默默地失败。 - Mick MacCallum
3
与其进行负面评分,我认为你应该提供任何可靠的方法来达成这个目标。如果它仍然在最新版本中运作正常,那么它很可能会继续长时间地运作。而且也不保证苹果公司会移除它或者保留它。所以如果能够得到我们想要的结果,为什么要犹豫呢?顺便说一下,在说“这不是一个好的解决方案”之后,请提供你自己的出色解决方案。 - Kiran Thapa
我已经在Swift 2.2中尝试过,但它不起作用并出现错误。self.txtFldFirstName.setValue(UIColor(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0), forKey: "_placeholderLabel.textColor")。类似这样的错误:类不符合键值编码_key placeholderLabel.textColor 的要求。 - Gautam Sareriya
@GautamSareriya:我在 Swift 3 中使用这段代码也遇到了崩溃,你有任何更新吗? - Tejinder
线程1:“禁止访问UITextField的_placeholderLabel ivar。这是一个应用程序错误。” - Omar N Shamali

2

Swift 4:

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

2
您可以创建Textfield的子类并重写DrawRect函数来实现。通过创建子类,您可以轻松地为每个文本字段设置相同的样式。
class CustomTextfield :UITextField {
 override func drawRect(rect: CGRect) {
self.attributedPlaceholder = NSAttributedString(string:self.placeholder != nil ? self.placeholder! : "", attributes:[NSForegroundColorAttributeName: UIColor.grayColor()])
} }

1

Swift 5

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接