Changing Placeholder Text Color with Swift

IosSwiftUikit

Ios Problem Overview


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 text says.

I've googled the problem of course but I have yet to come up with a solution while using the Swift language and not Obj-c.

Is there a way to change the placeholder text colour in a UITextField using Swift?

Ios Solutions


Solution 1 - Ios

You can set the placeholder text using an attributed string. Just pass the color you want to the attributes parameter.

Swift 5:

let myTextField = UITextField(frame: CGRect(x: 0, y: 0, width: 200, height: 30))
myTextField.backgroundColor = .blue
myTextField.attributedPlaceholder = NSAttributedString(
    string: "Placeholder Text",
    attributes: [NSAttributedString.Key.foregroundColor: UIColor.white]
)

Swift 3:

myTextField.attributedPlaceholder = NSAttributedString(
    string: "Placeholder Text",
    attributes: [NSAttributedStringKey.foregroundColor: UIColor.white]
)

Older Swift:

myTextField.attributedPlaceholder = NSAttributedString(
    string: "Placeholder Text",
    attributes: [NSForegroundColorAttributeName: UIColor.white]
)

Solution 2 - Ios

You can accomplish this quickly, without adding a line of code, using Interface Builder.

Select the UITextField and open the identity inspector on the right:

enter image description here

Click on the plus button and add a new runtime attribute:

placeholderLabel.textColor (Swift 4)

_placeholderLabel.textColor (Swift 3 or less)

Use Color as type and select the color.

That's it.

You wont see the result until you run your app again.

Solution 3 - Ios

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

enter image description here

Solution 4 - Ios

In Swift 3.0, Use

let color = UIColor.lightText
textField.attributedPlaceholder = NSAttributedString(string: textField.placeholder, attributes: [NSForegroundColorAttributeName : color])

In Siwft 5.0 + Use

let color = UIColor.lightText
let placeholder = textField.placeholder ?? "" //There should be a placeholder set in storyboard or elsewhere string or pass empty
textField.attributedPlaceholder = NSAttributedString(string: placeholder, attributes: [NSAttributedString.Key.foregroundColor : color])

Solution 5 - Ios

This code is working in Swift3:

yourTextFieldName .setValue(UIColor.init(colorLiteralRed: 80/255, green: 80/255, blue: 80/255, alpha: 1.0), forKeyPath: "_placeholderLabel.textColor")

let me know if you have any issue.

Solution 6 - Ios

To set the placeholder color once for all the UITextField in your app you can do:

UILabel.appearanceWhenContainedInInstancesOfClasses([UITextField.self]).textColor = UIColor.redColor()

This will set the desired color for all TextField placeholders in the entire app. But it is only available since iOS 9.

There is no appearenceWhenContainedIn....() method before iOS 9 in swift but you can use one of the solutions provided here https://stackoverflow.com/questions/24136874/appearancewhencontainedin-in-swift

Solution 7 - Ios

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)

Solution 8 - Ios

For Swift

Create UITextField Extension

extension UITextField{

    func setPlaceHolderColor(){
        self.attributedPlaceholder = NSAttributedString(string: self.placeholder!, attributes: [NSForegroundColorAttributeName : UIColor.white])
    }
}

If Are you set from storyboard.

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!])
        }
    }
}

Solution 9 - Ios

Xcode 9.2 Swift 4

extension UITextField{
    @IBInspectable var placeHolderColor: UIColor? {
        get {
            return self.placeHolderColor
        }
        set {
            self.attributedPlaceholder = NSAttributedString(string:self.placeholder != nil ? self.placeholder! : "", attributes:[NSAttributedStringKey.foregroundColor: newValue!])
        }
    }
}

Solution 10 - Ios

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}];

Solution 11 - Ios

Swift 3 (probably 2), you can override didSet on placeholder in UITextField subclass to apply attribute on it, this way:

override var placeholder: String? {
    
    didSet {
        guard let tmpText = placeholder else {
            self.attributedPlaceholder = NSAttributedString(string: "")
            return
        }

        let textRange = NSMakeRange(0, tmpText.characters.count)
        let attributedText = NSMutableAttributedString(string: tmpText)
        attributedText.addAttribute(NSForegroundColorAttributeName , value:UIColor(white:147.0/255.0, alpha:1.0), range: textRange)
        
        self.attributedPlaceholder = attributedText
    }
}

Solution 12 - Ios

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!

Solution 13 - Ios

For Swift 3 and 3.1 this works perfectly fine:

passField.attributedPlaceholder = NSAttributedString(string: "password", attributes: [NSForegroundColorAttributeName: UIColor.white])

Solution 14 - Ios

For Swift 4.0, X-code 9.1 version or iOS 11 you can use following syntax to have different placeholder color

textField.attributedPlaceholder = NSAttributedString(string: "Placeholder Text", attributes: [NSAttributedStringKey.foregroundColor : UIColor.white])

Solution 15 - Ios

I'm surprised to see how many poor solutions there are here.

Here is a version that will always work.

Swift 4.2

extension UITextField{
    @IBInspectable var placeholderColor: UIColor {
        get {
            return self.attributedPlaceholder?.attribute(.foregroundColor, at: 0, effectiveRange: nil) as? UIColor ?? .lightText
        }
        set {
            self.attributedPlaceholder = NSAttributedString(string: self.placeholder ?? "", attributes: [.foregroundColor: newValue])
        }
    }
}

TIP: If you change the placeholder text after setting the color- the color will reset.

Solution 16 - Ios

> Just write below code into Appdelegate's didFinishLaunchingWithOptions method use this if you want to change in the whole app written in Swift 4.2

UILabel.appearance(whenContainedInInstancesOf: [UITextField.self]).textColor = UIColor.white

Solution 17 - Ios

Here am i writing all UIDesignable of UITextField. With the help of this code you can directly access it from UI file Inspector in storyboard

@IBDesignable
class CustomTextField: UITextField {

@IBInspectable var leftImage: UIImage? {
    didSet {
        updateView()
    }
}

@IBInspectable var leftPadding: CGFloat = 0 {
    didSet {
        updateView()
    }
}

@IBInspectable var rightImage: UIImage? {
    didSet {
        updateView()
    }
}

@IBInspectable var rightPadding: CGFloat = 0 {
    didSet {
        updateView()
    }
}

private var _isRightViewVisible: Bool = true
var isRightViewVisible: Bool {
    get {
        return _isRightViewVisible
    }
    set {
        _isRightViewVisible = newValue
        updateView()
    }
}

func updateView() {
    setLeftImage()
    setRightImage()
    
    // Placeholder text color
    attributedPlaceholder = NSAttributedString(string: placeholder != nil ?  placeholder! : "", attributes:[NSAttributedString.Key.foregroundColor: tintColor])
}

func setLeftImage() {
    leftViewMode = UITextField.ViewMode.always
    var view: UIView
    
    if let image = leftImage {
        let imageView = UIImageView(frame: CGRect(x: leftPadding, y: 0, width: 20, height: 20))
        imageView.image = image
        // Note: In order for your image to use the tint color, you have to select the image in the Assets.xcassets and change the "Render As" property to "Template Image".
        imageView.tintColor = tintColor
        
        var width = imageView.frame.width + leftPadding
        
        if borderStyle == UITextField.BorderStyle.none || borderStyle == UITextField.BorderStyle.line {
            width += 5
        }
        
        view = UIView(frame: CGRect(x: 0, y: 0, width: width, height: 20))
        view.addSubview(imageView)
    } else {
        view = UIView(frame: CGRect(x: 0, y: 0, width: leftPadding, height: 20))
    }
    
    leftView = view
}

func setRightImage() {
    rightViewMode = UITextField.ViewMode.always
    
    var view: UIView
    
    if let image = rightImage, isRightViewVisible {
        let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 20, height: 20))
        imageView.image = image
        // Note: In order for your image to use the tint color, you have to select the image in the Assets.xcassets and change the "Render As" property to "Template Image".
        imageView.tintColor = tintColor
        
        var width = imageView.frame.width + rightPadding
        
        if borderStyle == UITextField.BorderStyle.none || borderStyle == UITextField.BorderStyle.line {
            width += 5
        }
        
        view = UIView(frame: CGRect(x: 0, y: 0, width: width, height: 20))
        view.addSubview(imageView)
        
    } else {
        view = UIView(frame: CGRect(x: 0, y: 0, width: rightPadding, height: 20))
    }
    
    rightView = view
}


@IBInspectable public var borderColor: UIColor = UIColor.clear {
    didSet {
        layer.borderColor = borderColor.cgColor
    }
}

@IBInspectable public var borderWidth: CGFloat = 0 {
    didSet {
        layer.borderWidth = borderWidth
    }
}

@IBInspectable public var cornerRadius: CGFloat = 0 {
    didSet {
        layer.cornerRadius = cornerRadius
    }
}
@IBInspectable public var bottomBorder: CGFloat = 0 {
    didSet {
       borderStyle = .none
        layer.backgroundColor = UIColor.white.cgColor
        
        layer.masksToBounds = false
     //   layer.shadowColor = UIColor.gray.cgColor
        layer.shadowOffset = CGSize(width: 0.0, height: 1.0)
        layer.shadowOpacity = 1.0
        layer.shadowRadius = 0.0
    }
}
@IBInspectable public var bottomBorderColor : UIColor = UIColor.clear {
    didSet {
     
        layer.shadowColor = bottomBorderColor.cgColor
        layer.shadowOffset = CGSize(width: 0.0, height: 1.0)
        layer.shadowOpacity = 1.0
        layer.shadowRadius = 0.0
    }
}
/// Sets the placeholder color
@IBInspectable var placeHolderColor: UIColor? {
    get {
        return self.placeHolderColor
    }
    set {
        self.attributedPlaceholder = NSAttributedString(string:self.placeholder != nil ? self.placeholder! : "", attributes:[NSAttributedString.Key.foregroundColor: newValue!])
    }
}

}

Solution 18 - Ios

Use like this in Swift,

 let placeHolderText = textField.placeholder ?? ""
 let str = NSAttributedString(string:placeHolderText!, attributes: [NSAttributedString.Key.foregroundColor :UIColor.lightGray])
 textField.attributedPlaceholder = str

In Objective C

NSString *placeHolder = [textField.placeholder length]>0 ? textField.placeholder: @"";
NSAttributedString *str = [[NSAttributedString alloc] initWithString:placeHolder attributes:@{ NSForegroundColorAttributeName : [UIColor lightGrayColor] }];
textField.attributedPlaceholder = str;

Solution 19 - Ios

In my case, I had to make the placeholder into black color. The name of my UITextField is passwordText. Below code is tested in Swift 5 and is working fine for me. I also had an existing text for the corresponding placeholder.

let placeholderColor = UIColor.black
passwordText.attributedPlaceholder = NSAttributedString(string: passwordText.placeholder!, attributes: [NSAttributedString.Key.foregroundColor : placeholderColor])

Solution 20 - Ios

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.

Solution 21 - Ios

For swift 4.2 and above you can do it as below:

textField.attributedPlaceholder = NSAttributedString(string: "Placeholder Text", attributes: [NSAttributedString.Key.foregroundColor: UIColor.white])

Solution 22 - Ios

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])
            }
        }
    }
}

Solution 23 - Ios

    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!])
                }
            } 
}

Solution 24 - Ios

For Swift

func setPlaceholderColor(textField: UITextField, placeholderText: String) {
    textField.attributedPlaceholder = NSAttributedString(string: placeholderText, attributes: [NSForegroundColorAttributeName: UIColor.pelorBlack])
}

You can use this;

self.setPlaceholderColor(textField: self.emailTextField, placeholderText: "E-Mail/Username")

Solution 25 - Ios

It is more about personalize your textField but anyways I'll share this code got from another page and made it a little better:

import UIKit
extension UITextField {
func setBottomLine(borderColor: UIColor, fontColor: UIColor, placeHolderColor:UIColor, placeHolder: String) {
    self.borderStyle = UITextBorderStyle.none
    self.backgroundColor = UIColor.clear
    let borderLine = UIView()
    let height = 1.0
    borderLine.frame = CGRect(x: 0, y: Double(self.frame.height) - height, width: Double(self.frame.width), height: height)
    self.textColor = fontColor
    borderLine.backgroundColor = borderColor
    self.addSubview(borderLine)
    self.attributedPlaceholder = NSAttributedString(
        string: placeHolder,
        attributes: [NSAttributedStringKey.foregroundColor: placeHolderColor]
    )
  }
}

And you can use it like this:

self.textField.setBottomLine(borderColor: lineColor, fontColor: fontColor, placeHolderColor: placeHolderColor, placeHolder: placeHolder)

Knowing that you have an UITextField connected to a ViewController.

Source: http://codepany.com/blog/swift-3-custom-uitextfield-with-single-line-input/

Solution 26 - Ios

enter image description here

For Objective C:

UIColor *color = [UIColor colorWithRed:0.44 green:0.44 blue:0.44 alpha:1.0];
 emailTextField.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"Friend's Email" attributes:@{NSForegroundColorAttributeName: color}];

For Swift:

emailTextField.attributedPlaceholder = NSAttributedString(string: "Friend's Email",
                             attributes: [NSAttributedString.Key.foregroundColor: UIColor.white])

Solution 27 - Ios

Objective C code for changing placeholder text color.

First import this objc/runtime class -

#import <objc/runtime.h>

then replace your textfield name -

Ivar ivar =  class_getInstanceVariable([UITextField class], "_placeholderLabel");
UILabel *placeholderLabel = object_getIvar(YourTxtField, ivar);
placeholderLabel.textColor = [UIColor whiteColor];

Solution 28 - Ios

for iOS13

+(void)ChangeplaceholderColor :(UITextField *)TxtFld andColor:(UIColor*)color { 
    NSMutableAttributedString *placeholderAttributedString = [[NSMutableAttributedString alloc] initWithAttributedString:TxtFld.attributedPlaceholder];
       [placeholderAttributedString addAttribute:NSForegroundColorAttributeName value:color range:NSMakeRange(0, [placeholderAttributedString length])];
       TxtFld.attributedPlaceholder = placeholderAttributedString;
    
}

Solution 29 - Ios

Use this for adding an attributed placeholder:

let attributes : [String : Any]  = [ NSForegroundColorAttributeName: UIColor.lightGray,
                                     NSFontAttributeName : UIFont(name: "Helvetica Neue Light Italic", size: 12.0)!
                                   ]
x_textfield.attributedPlaceholder = NSAttributedString(string: "Placeholder Text", attributes:attributes)

Solution 30 - Ios

For Swift 4

txtField1.attributedPlaceholder = NSAttributedString(string: "-", attributes: [NSAttributedStringKey.foregroundColor: UIColor.white])

Solution 31 - Ios

yourTextfield.attributedPlaceholder = NSAttributedString(string: "your placeholder text",attributes: [NSForegroundColorAttributeName: UIColor.white])

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAlex CatchpoleView Question on Stackoverflow
Solution 1 - IosvacawamaView Answer on Stackoverflow
Solution 2 - IoscrubioView Answer on Stackoverflow
Solution 3 - Iosjose920405View Answer on Stackoverflow
Solution 4 - IosSreedeepkesav M SView Answer on Stackoverflow
Solution 5 - IosTejinderView Answer on Stackoverflow
Solution 6 - IosKrzynoolView Answer on Stackoverflow
Solution 7 - IosRidho OctanioView Answer on Stackoverflow
Solution 8 - IosDixit AkabariView Answer on Stackoverflow
Solution 9 - IosKhawar IslamView Answer on Stackoverflow
Solution 10 - IosÁlvaro AgüeroView Answer on Stackoverflow
Solution 11 - Iosninja_iOSView Answer on Stackoverflow
Solution 12 - IosPaul LehnView Answer on Stackoverflow
Solution 13 - IosAsfand ShabbirView Answer on Stackoverflow
Solution 14 - IosAshim DahalView Answer on Stackoverflow
Solution 15 - IosDavid ReesView Answer on Stackoverflow
Solution 16 - IosiOS LifeeView Answer on Stackoverflow
Solution 17 - IosVikas RajputView Answer on Stackoverflow
Solution 18 - IosSureshkumar LinganathanView Answer on Stackoverflow
Solution 19 - IosJuvinRView Answer on Stackoverflow
Solution 20 - IosDrisView Answer on Stackoverflow
Solution 21 - IosAnindyaView Answer on Stackoverflow
Solution 22 - IosPradip PatelView Answer on Stackoverflow
Solution 23 - IosDilip MishraView Answer on Stackoverflow
Solution 24 - IosCelil BozkurtView Answer on Stackoverflow
Solution 25 - IosAndres PaladinesView Answer on Stackoverflow
Solution 26 - IosMr.Javed MultaniView Answer on Stackoverflow
Solution 27 - IosA K M Saleh SultanView Answer on Stackoverflow
Solution 28 - IosJigarView Answer on Stackoverflow
Solution 29 - IosCodewithjView Answer on Stackoverflow
Solution 30 - IosArjun DobariaView Answer on Stackoverflow
Solution 31 - IosDurga Ballabha PanigrahiView Answer on Stackoverflow