繁体   English   中英

UITextField占位符颜色

[英]UITextField Placeholder Color

我完全意识到,已经有多个答案。 我添加了运行时属性。 我还添加了UITextField扩展。 占位符颜色仍然拒绝在模拟器和设备上更改。 我不是通过情节提要设置占位符。 正在通过从数据库检索数据来设置占位符文本。 为什么我的占位符颜色不会更改?

在此处输入图片说明

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

你有几个问题。

您调用self.nameTextField.placeholder = username 这会清除掉您可能拥有的所有属性占位符,并恢复为默认颜色。 您需要在设置placeholder之后设置placeHolderColor才能看到颜色。

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM