How to dynamically change placeholder color of the UITextField
?
This is always the same system color.
No option in xib editor.
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
You can use the following code
[txtUsername setValue:[UIColor darkGrayColor] forKeyPath:@"_placeholderLabel.textColor"];
Swift 4
let placeholderColor = UIColor.red
self.passwordTextField?.attributedPlaceholder =
NSAttributedString(string:"placeholderText", attributes:
[NSAttributedStringKey.foregroundColor : placeholderColor])
This solution works without any subclassing and without any private ivars:
@IBOutlet weak var emailTextField: UITextField! {
didSet {
if emailTextField != nil {
let placeholderText = NSLocalizedString("Tap here to enter", comment: "Tap here to enter")
let placeholderString = NSAttributedString(string: placeholderText, attributes: [NSForegroundColorAttributeName: UIColor(white: 0.66, alpha: 1.0)])
emailTextField.attributedPlaceholder = placeholderString
}
}
}
Try This.
UIColor *color = [UIColor redColor];
self.txtUsername.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"Your Placeholder Text" attributes:@{NSForegroundColorAttributeName:color}];
_placeholderLabel.textColor
In swift
myTextField.attributedPlaceholder =
NSAttributedString(string: "placeholder", attributes:[NSForegroundColorAttributeName : UIColor.redColor()])
Objective-C
UIColor *color = [UIColor grayColor];
nameText.attributedPlaceholder =
[[NSAttributedString alloc]
initWithString:@"Full Name"
attributes:@{NSForegroundColorAttributeName:color}];
P.S Copied 3 different answers from Stackoverflow.