Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing Placeholder Text Color with Swift

Tags:

ios

uikit

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?

like image 748
Alex Catchpole Avatar asked Sep 27 '14 15:09

Alex Catchpole


People also ask

How do I change placeholder color in Swift?

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

How can I change the color of placeholder of text field?

<input type="text" placeholder="A red placeholder text..">

How do I change the placeholder color on a storyboard?

The easiest method to modify the placeholder text color is through the Xcode storyboard interface builder. Select the UITextField of interest and open the identity inspector on the right. Click on the plus symbol in the User Defined Runtime Attributes and add a new row with Key Path as placeholderLabel.


1 Answers

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] ) 
like image 186
vacawama Avatar answered Sep 23 '22 06:09

vacawama