Changing Placeholder Text Color with Swift

前端 未结 30 2481
独厮守ぢ
独厮守ぢ 2020-11-29 15:57

I have a design that implements a dark blue UITextField, as the placeholder text is by default a dark grey colour I can barely make out what the place holder te

30条回答
  •  独厮守ぢ
    2020-11-29 16:00

    You can set the placeholder text using an attributed string. Pass the color you want with the attributes:

    var myTextField = UITextField(frame: CGRect(x: 0, y: 0, width: 200, height: 30))
    myTextField.backgroundColor = .blue
    myTextField.attributedPlaceholder = NSAttributedString(string: "placeholder text",
                                 attributes: [NSForegroundColorAttributeName: UIColor.yellow])
    

    For Swift 3+ use following:

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

    For Swift 4.2 use following:

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

提交回复
热议问题