Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set UITextField placeholder color programmatically

How to set UITextField place holder color programmatically in swift?

like image 683
user3823935 Avatar asked Sep 05 '14 05:09

user3823935


2 Answers

1 - Create an AttributedString with colour you want.
2 - Set this AttributedString to the textfield attributedPlaceholder property

let placeholder = NSAttributedString(string: "Some", attributes: [NSForegroundColorAttributeName : UIColor.redColor()])
let textField = UITextField(frame: CGRect(x: 0, y: 0, width: 100, height: 30));
textField.attributedPlaceholder = placeholder;
self.view.addSubview(textField)

From apple documentation

var attributedPlaceholder: NSAttributedString!
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.

like image 123
Kostiantyn Koval Avatar answered Oct 27 '22 18:10

Kostiantyn Koval


captionField = UITextField()
captionField.frame = CGRectMake(0, 0, 100, 40)
var placeHolder = NSAttributedString(string: "Enter caption", attributes: [NSForegroundColorAttributeName: UIColor.redColor()])
captionField.attributedPlaceholder = placeHolder
captionField.textColor = UIColor.whiteColor()
like image 35
Raees Valapuram Madathil Avatar answered Oct 27 '22 19:10

Raees Valapuram Madathil