-->

Set UITextField placeholder color programmatically

2020-08-17 17:49发布

问题:

How to set UITextField place holder color programmatically in swift?

回答1:

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.



回答2:

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()


回答3:

if you need to add alpha value:

var placeholder = NSAttributedString(string: "Password", attributes: [NSForegroundColorAttributeName : UIColor(white: 0.6, alpha: 0.5)])