Changing Placeholder Text Color with Swift
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 text says.
I've googled the problem of course but I have yet to come up with a solution while using the Swift language and not Obj-c.
Is there a way to change the placeholder text colour in a UITextField
using 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:
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