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

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

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


当前回答

在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])

其他回答

在我的例子中,我必须将占位符设置为黑色。UITextField的名字是passwordText。下面的代码是在Swift 5中测试的,对我来说工作得很好。我也有一个现有的文本对应的占位符。

let placeholderColor = UIColor.black
passwordText.attributedPlaceholder = NSAttributedString(string: passwordText.placeholder!, attributes: [NSAttributedString.Key.foregroundColor : placeholderColor])

Xcode 9.2 Swift 4

extension UITextField{
    @IBInspectable var placeHolderColor: UIColor? {
        get {
            return self.placeHolderColor
        }
        set {
            self.attributedPlaceholder = NSAttributedString(string:self.placeholder != nil ? self.placeholder! : "", attributes:[NSAttributedStringKey.foregroundColor: newValue!])
        }
    }
}

为迅速

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

你可以用这个;

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

crubio对Swift 4的答案更新

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

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

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

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

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

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