UITextField占位符颜色

时间:2018-05-28 22:24:39

标签: ios swift uitextfield

我完全清楚已经有多个答案。我添加了运行时属性。我还添加了一个UITextField扩展。占位符颜色仍然拒绝在模拟器和设备上更改。我没有通过故事板设置占位符。通过从数据库中检索数据来设置占位符文本。为什么我的占位符颜色会发生变化?

enter image description here

extension UITextField{
@IBInspectable var placeHolderColor: UIColor? {
    get {
        return self.placeHolderColor
    }
    set {
        self.attributedPlaceholder = NSAttributedString(string:self.placeholder != nil ? self.placeholder! : "", attributes:[kCTForegroundColorAttributeName as NSAttributedStringKey: newValue!])
    }
}
  }
            func loadUserInfo(){
        if let username = user.name{
            self.nameLabel.text = username
            self.nameTextField.placeholder = username
           print(username)
        }

2 个答案:

答案 0 :(得分:1)

你有一些问题。

您致电self.nameTextField.placeholder = username。这会清除您可能拥有的任何属性占位符,并返回默认颜色。设置placeHolderColor后,您需要设置placeholder才能看到颜色。

get计算属性的placeHolderColor将导致无限递归,因为它调用self.placeHolderColor调用调用getter的self.placeHolderColor调用getter的getter ...

答案 1 :(得分:0)

在获取用户名后的loadUserInfo中,我添加了self.nameTextField.attributedPlaceholder = NSAttributedString(string:user.name, attributes: [NSAttributedStringKey.foregroundColor: UIColor.green])

相关问题