swift设置UITextfield的Placeholder字体
2019-08-08 本文已影响0人
SwiftDev
常用设置方式
方式一
textFiled.setValue(UIColor.lightGray, forKey: "_placeholderLabel.textColor")
textFiled.setValue(UIFont.systemFont(ofSize: 15), forKeyPath: "_placeholderLabel.font")
方式二
// 字体大小
textField.attributedPlaceholder = NSAttributedString.init(string:"请输入卡号", attributes: [NSAttributedString.Key.font:UIFont.systemFont(ofSize:12)])
//字体颜色
textField.attributedPlaceholder = NSAttributedString.init(string:"请输入卡号", attributes: [
NSAttributedString.Key.foregroundColor:UIColor.red])
这里有一个小坑需要注意:
在swift实际开发中我是这样写的
lazy var textField: UITextField = {
let textField = UITextField(frame: CGRect(x: 100, y: 100, width: 300, height: 50))
textField.placeholder = "请输入卡号"
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
}()
这样写的话,设置的placeholder的字体大小不会生效,颜色可以生效
原因:设置字体大小的顺序有问题
// 这句话一定要放在设置placeholder字体大小的前面
textField.font = UIFont.systemFont(ofSize: 24)
// 这句话一定要放在后面,否则会导致设置placeholder字体大小无效
textField.setValue(UIFont.systemFont(ofSize: 12), forKeyPath: "_placeholderLabel.font")
如果设置字体大小无效,检查这两行代码是否正确