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 te
In my case, I use Swift 4
I create extension for UITextField
extension UITextField {
func placeholderColor(color: UIColor) {
let attributeString = [
NSAttributedStringKey.foregroundColor: color.withAlphaComponent(0.6),
NSAttributedStringKey.font: self.font!
] as [NSAttributedStringKey : Any]
self.attributedPlaceholder = NSAttributedString(string: self.placeholder!, attributes: attributeString)
}
}
yourField.placeholderColor(color: UIColor.white)
crubio's answer update for Swift 4
Select the UITextField and open the identity inspector on the right:
Click on the plus button and add a new runtime attribute: placeholderLabel.textColor (instead of _placeholderLabel.textColor)
Use Color as type and select the color.
If you run your project, you will see the changes.
In my case, I have done following:
extension UITextField {
@IBInspectable var placeHolderColor: UIColor? {
get {
if let color = self.attributedPlaceholder?.attribute(.foregroundColor, at: 0, effectiveRange: nil) as? UIColor {
return color
}
return nil
}
set (setOptionalColor) {
if let setColor = setOptionalColor {
let string = self.placeholder ?? ""
self.attributedPlaceholder = NSAttributedString(string: string , attributes:[NSAttributedString.Key.foregroundColor: setColor])
}
}
}
}
Create UITextField
Extension like this:
extension UITextField{
@IBInspectable var placeHolderColor: UIColor? {
get {
return self.placeHolderColor
}
set {
self.attributedPlaceholder = NSAttributedString(string:self.placeholder != nil ? self.placeholder! : "", attributes:[NSAttributedString.Key.foregroundColor: newValue!])
}
}
}
And in your storyboard or .xib. You will see
Here is my quick implementation for swift 4:
extension UITextField {
func placeholderColor(_ color: UIColor){
var placeholderText = ""
if self.placeholder != nil{
placeholderText = self.placeholder!
}
self.attributedPlaceholder = NSAttributedString(string: placeholderText, attributes: [NSAttributedStringKey.foregroundColor : color])
}
}
use like:
streetTextField?.placeholderColor(AppColor.blueColor)
hope it helps someone!
Swift 4 :
txtControl.attributedPlaceholder = NSAttributedString(string: "Placeholder String...",attributes: [NSAttributedStringKey.foregroundColor: UIColor.gray])
Objective-C :
UIColor *color = [UIColor grayColor];
txtControl.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"Placeholder String..." attributes:@{NSForegroundColorAttributeName: color}];