Change placeholder text color on swift

14,928

Solution 1

You can set the placeholder text using an Attributed string. Set color to attributes Property.

   textField.attributedPlaceholder = NSAttributedString(string:"placeholder text",
   attributes:[NSForegroundColorAttributeName: UIColor.yellowColor()])

Swift 5

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

Solution 2

enter image description here

Click on the + button and add a new runtime attribute: _placeholderLabel.textColor

Run your app.

Solution 3

In swift you can change the placeholderColor by using the code,

 name_textField .setValue(UIColor.redColor(), forKeyPath: "_placeholderLabel.textColor")

Solution 4

You can create Subclass of Textfield and can override DrawRect function of textfield. By creating subclass you can set that for every textfields Easily.

class CustomTextfield :UITextField {
 override func drawRect(rect: CGRect) {
self.attributedPlaceholder = NSAttributedString(string:self.placeholder != nil ? self.placeholder! : "", attributes:[NSForegroundColorAttributeName: UIColor.grayColor()])
} }

Solution 5

Swift 4:

emailTextField.attributedPlaceholder = NSAttributedString(string: "e-mail", attributes: [NSAttributedStringKey.foregroundColor : UIColor.white])
Share:
14,928

Related videos on Youtube

user2585611
Author by

user2585611

Updated on September 14, 2022

Comments

  • user2585611
    user2585611 over 1 year

    How do I change the placeholder text color of a UITextField through Swift? I can't seem to access the placeholder attribute. Thanks

  • Mick MacCallum
    Mick MacCallum over 9 years
    This is not a good solution. Using this method, you can't guarentee App Store approval and it could silently break in a future iOS version.
  • Kiran Thapa
    Kiran Thapa over 9 years
    Rather than down voting, i think you should suggest any fail safe methods to achieve this. If it is still working in the latest versions, it is highly likely that it will continue to work for a long time. And there is no guarantee that Apple will remove it or keep it. So if it gets us the desired result, why hesitate? By the way, after saying "This is not a good solution" please provide your solution that works brilliantly.
  • Gautam Sareriya
    Gautam Sareriya almost 8 years
    I have tried it in Swift 2.2 but its not working and getting and error. self.txtFldFirstName.setValue(UIColor(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0), forKey: "_placeholderLabel.textColor") getting an error like this class is not key value coding-compliant for the key _placeholderLabel.textColor
  • Tejinder
    Tejinder over 7 years
    @GautamSareriya: I am also getting crash for this code in swift 3, do you have any update?