常用設(shè)置方式
方式一
textFiled.setValue(UIColor.lightGray, forKey: "_placeholderLabel.textColor")
textFiled.setValue(UIFont.systemFont(ofSize: 15), forKeyPath: "_placeholderLabel.font")
方式二
// 字體大小
textField.attributedPlaceholder = NSAttributedString.init(string:"請(qǐng)輸入卡號(hào)", attributes: [NSAttributedString.Key.font:UIFont.systemFont(ofSize:12)])
//字體顏色
textField.attributedPlaceholder = NSAttributedString.init(string:"請(qǐng)輸入卡號(hào)", attributes: [
NSAttributedString.Key.foregroundColor:UIColor.red])
這里有一個(gè)小坑需要注意:
在swift實(shí)際開發(fā)中我是這樣寫的
lazy var textField: UITextField = {
let textField = UITextField(frame: CGRect(x: 100, y: 100, width: 300, height: 50))
textField.placeholder = "請(qǐng)輸入卡號(hào)"
textField.setValue(UIColor.red, forKeyPath: "_placeholderLabel.textColor")
textField.setValue(UIFont.systemFont(ofSize: 12), forKeyPath: "_placeholderLabel.font")
textField.clearButtonMode = .whileEditing
textField.font = UIFont.systemFont(ofSize: 24)
textField2.delegate = self
view.addSubview(textField)
return textField
}()
這樣寫的話间护,設(shè)置的placeholder的字體大小不會(huì)生效蕉堰,顏色可以生效
原因:設(shè)置字體大小的順序有問題
// 這句話一定要放在設(shè)置placeholder字體大小的前面
textField.font = UIFont.systemFont(ofSize: 24)
// 這句話一定要放在后面访得,否則會(huì)導(dǎo)致設(shè)置placeholder字體大小無效
textField.setValue(UIFont.systemFont(ofSize: 12), forKeyPath: "_placeholderLabel.font")
如果設(shè)置字體大小無效围小,檢查這兩行代碼是否正確