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

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

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


当前回答

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

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

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

placeholderLabel。textColor (Swift 4)

_placeholderLabel。textColor (Swift 3或更少)

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

就是这样。

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

其他回答

这段代码在Swift3中工作:

yourTextFieldName .setValue(UIColor.init(colorLiteralRed: 80/255, green: 80/255, blue: 80/255, alpha: 1.0), forKeyPath: "_placeholderLabel.textColor")

如果你有任何问题,请告诉我。

为迅速

func setPlaceholderColor(textField: UITextField, placeholderText: String) {
    textField.attributedPlaceholder = NSAttributedString(string: placeholderText, attributes: [NSForegroundColorAttributeName: UIColor.pelorBlack])
}

你可以用这个;

self.setPlaceholderColor(textField: self.emailTextField, placeholderText: "E-Mail/Username")

在Swift 3.0中,使用

let color = UIColor.lightText
textField.attributedPlaceholder = NSAttributedString(string: textField.placeholder, attributes: [NSForegroundColorAttributeName : color])

在Siwft 5.0 +使用

let color = UIColor.lightText
let placeholder = textField.placeholder ?? "" //There should be a placeholder set in storyboard or elsewhere string or pass empty
textField.attributedPlaceholder = NSAttributedString(string: placeholder, attributes: [NSAttributedString.Key.foregroundColor : color])

只要把下面的代码写进Appdelegate的didFinishLaunchingWithOptions方法,如果你想在Swift 4.2编写的整个应用程序中进行更改,使用这个方法

UILabel.appearance(whenContainedInInstancesOf: [UITextField.self]).textColor = UIColor.white

crubio对Swift 4的答案更新

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

单击加号按钮并添加一个新的运行时属性:placeholderLabel。textColor(代替_placeholderLabel.textColor)

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

如果您运行您的项目,您将看到这些更改。