Change of UITextField placeholder color

theWalker picture theWalker · Jan 12, 2014 · Viewed 69.5k times · Source

How to dynamically change placeholder color of the UITextField? This is always the same system color.

No option in xib editor.

Answer

DogCoffee picture DogCoffee · Jan 12, 2014

From Docs

@property(nonatomic, copy) NSAttributedString *attributedPlaceholder

This property is nil by default. If set, the placeholder string is drawn using a 70% grey color and the remaining style information (except the text color) of the attributed string. Assigning a new value to this property also replaces the value of the placeholder property with the same string data, albeit without any formatting information. Assigning a new value to this property does not affect any other style-related properties of the text field.

Objective-C

NSAttributedString *str = [[NSAttributedString alloc] initWithString:@"Some Text" attributes:@{ NSForegroundColorAttributeName : [UIColor redColor] }];
self.myTextField.attributedPlaceholder = str;

Swift

let str = NSAttributedString(string: "Text", attributes: [NSForegroundColorAttributeName:UIColor.redColor()])
myTextField.attributedPlaceholder = str

Swift 4

let str = NSAttributedString(string: "Text", attributes: [NSAttributedString.Key.foregroundColor: UIColor.red])
myTextField.attributedPlaceholder = str