Change the colour of Placeholder using these 3 Methods

Posted By : Aditya Kumar Sharma | 27-Jun-2017

First we will be proceeding with Changing placeholder colour with Swift and for that we have to follow these steps:

 

Create an outlet of the textField.

   @IBOutlet weak var textField: UITextField!

 

Now in ViewDidLoad() take a NSMutuableAttributedString()

   var placeHolder = NSMutableAttributedString()

 

Now for this AttributedString we will be setting font and colour.

// Set the Font 
placeHolder = NSMutableAttributedString(string: “Placeholder”, attributes: [NSFontAttributeName:UIFont(name: "Helvetica", size: 15.0)!])

// Set the color
placeHolder.addAttribute(NSForegroundColorAttributeName, value: UIColor.redColor(), range:NSRange(location:0,length:Name.characters.count))   

 

Last step is to add this attributedString to textfield

// Add attribute        
textField.attributedPlaceholder = placeHolder

 

Run the app and see the placeholder.

 

 

 

Second way will be Swift Extensions:

 

Go to Storyboard and set the placeholder for the textfield from attribute inspector.

 

Now we will be adding extension for UITextField in ViewController.

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

 

So add this in ViewController.Swift and it must be out of class declaration scope.

 

Again go back to Main.Storyboard we will find a new option for setting textfield placeholder colour. Set it and Run the code.

 

 

 

Third and the final way is by using User Defined Runtime Attributes:

 

For this we have to go to Main.Storyboard and select the textfield.

 

After selecting textfield we have to go to Identity Inspector and scroll down to User Defined Runtime Attributes.

 

                       

 

There we have to add new row and values

       _placeholderLabel.textColor	Color	Select a color

 

And there you get it.

 

 

Thanks

 

About Author

Author Image
Aditya Kumar Sharma

Aditya is a bright iOS developer, have knowledge of objective C, swift, swift 3, JSON, Core data and iPhone development. Apart from that he loves to travel and explore new things.

Request for Proposal

Name is required

Comment is required

Sending message..