How to dynamically change placeholder color of the UITextField
? This is always the same system color.
No option in xib editor.
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.
You can set the placeholder text using an attributed string. Just pass the color you want to the attributes parameter.
Note: In most browsers, the appearance of placeholder text is a translucent or light gray color by default.
TextField view doesn't provide a way to add background color but we can use the background modifier to add color to the TextField.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With