Set UITextField placeholder color programmatically

本小妞迷上赌 提交于 2019-12-05 02:50:41

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.

Raees Valapuram Madathil
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()
Satnam Sync

if you need to add alpha value:

var placeholder = NSAttributedString(string: "Password", attributes: [NSForegroundColorAttributeName : UIColor(white: 0.6, alpha: 0.5)])
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!