Changing Placeholder Text Color with Swift

You can set the placeholder text using an attributed string. Just pass the color you want to the attributes parameter.

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

Swift 3:

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

Older Swift:

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

You can accomplish this quickly, without adding a line of code, using Interface Builder.

Select the UITextField and open the identity inspector on the right:

enter image description here

Click on the plus button and add a new runtime attribute:

placeholderLabel.textColor (Swift 4)

_placeholderLabel.textColor (Swift 3 or less)

Use Color as type and select the color.

That's it.

You wont see the result until you run your app again.


Create UITextField Extension like this:

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

And in your storyboard or .xib. You will see

enter image description here

Tags:

Ios

Uikit

Swift