以编程方式更改占位符文本颜色

时间:2018-09-19 20:31:21

标签: swift uitextfield

我正在尝试将文本字段中的占位符文本更改为白色,背景色为黑色。以编程方式

这是我的代码

let emailTextField: UITextField = {
    let emailTF = UITextField()
    emailTF.attributedPlaceholder = NSAttributedString(string: "Enter Email", attributes: [kCTForegroundColorAttributeName as NSAttributedStringKey: kCISamplerWrapBlack])

    emailTF.translatesAutoresizingMaskIntoConstraints = false
    //User input text white
    emailTF.textColor = UIColor.white
    emailTF.backgroundColor = UIColor.black
    emailTF.borderStyle = .roundedRect
    emailTF.font = UIFont.systemFont(ofSize: 16)
    return emailTF
}()

谢谢。

2 个答案:

答案 0 :(得分:0)

尝试一下:

let emailTextField: UITextField = {
        let emailTF = UITextField()
        emailTF.attributedPlaceholder = NSAttributedString(string: "Enter Email",
                                                            attributes: [NSAttributedStringKey.foregroundColor: UIColor.white])

        emailTF.translatesAutoresizingMaskIntoConstraints = false
        //User input text white
        emailTF.textColor = UIColor.white
        emailTF.backgroundColor = UIColor.black
        emailTF.borderStyle = .roundedRect
        emailTF.font = UIFont.systemFont(ofSize: 16)
        return emailTF
  }()

答案 1 :(得分:-4)

您可以尝试一下(Swift 4.1)

emailTF.attributedPlaceholder = NSAttributedString(string:"Enter Email", attributes: [NSAttributedStringKey.foregroundColor:UIColor.white,NSAttributedStringKey.backgroundColor:UIColor.black])