我有一个实现深蓝色UITextField的设计,因为占位符文本默认是深灰色的颜色,我几乎不能弄清楚占位符文本说什么。

我当然在谷歌上搜索过这个问题,但我还没有想出一个解决方案,而使用Swift语言而不是Obj-c。

有没有一种方法来改变一个UITextField的占位符文本颜色使用Swift?


当前回答

您可以使用带属性的字符串设置占位符文本。只需要把你想要的颜色传递给属性参数。

斯威夫特5:

let myTextField = UITextField(frame: CGRect(x: 0, y: 0, width: 200, height: 30))
myTextField.backgroundColor = .blue
myTextField.attributedPlaceholder = NSAttributedString(
    string: "Placeholder Text",
    attributes: [NSAttributedString.Key.foregroundColor: UIColor.white]
)

斯威夫特3:

myTextField.attributedPlaceholder = NSAttributedString(
    string: "Placeholder Text",
    attributes: [NSAttributedStringKey.foregroundColor: UIColor.white]
)

年长的迅速:

myTextField.attributedPlaceholder = NSAttributedString(
    string: "Placeholder Text",
    attributes: [NSForegroundColorAttributeName: UIColor.white]
)

其他回答

您可以使用带属性的字符串设置占位符文本。只需要把你想要的颜色传递给属性参数。

斯威夫特5:

let myTextField = UITextField(frame: CGRect(x: 0, y: 0, width: 200, height: 30))
myTextField.backgroundColor = .blue
myTextField.attributedPlaceholder = NSAttributedString(
    string: "Placeholder Text",
    attributes: [NSAttributedString.Key.foregroundColor: UIColor.white]
)

斯威夫特3:

myTextField.attributedPlaceholder = NSAttributedString(
    string: "Placeholder Text",
    attributes: [NSAttributedStringKey.foregroundColor: UIColor.white]
)

年长的迅速:

myTextField.attributedPlaceholder = NSAttributedString(
    string: "Placeholder Text",
    attributes: [NSForegroundColorAttributeName: UIColor.white]
)

您可以使用Interface Builder快速完成此任务,而无需添加一行代码。

选择UITextField并打开右边的标识检查器:

点击加号按钮,添加一个新的运行时属性:

placeholderLabel。textColor (Swift 4)

_placeholderLabel。textColor (Swift 3或更少)

使用颜色作为类型并选择颜色。

就是这样。

你不会看到结果,直到你再次运行你的应用程序。

对于Swift 3和3.1,这工作得非常好:

passField.attributedPlaceholder = NSAttributedString(string: "password", attributes: [NSForegroundColorAttributeName: UIColor.white])

添加带属性的占位符:

let attributes : [String : Any]  = [ NSForegroundColorAttributeName: UIColor.lightGray,
                                     NSFontAttributeName : UIFont(name: "Helvetica Neue Light Italic", size: 12.0)!
                                   ]
x_textfield.attributedPlaceholder = NSAttributedString(string: "Placeholder Text", attributes:attributes)
yourTextfield.attributedPlaceholder = NSAttributedString(string: "your placeholder text",attributes: [NSForegroundColorAttributeName: UIColor.white])