【问题标题】:UITextField Placeholder ColorUITextField 占位符颜色
【发布时间】:2018-05-28 22:24:39
【问题描述】:

我完全意识到已经有多个答案。我添加了运行时属性。我还添加了一个 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)
        }

【问题讨论】:

    标签: ios swift uitextfield


    【解决方案1】:

    你有一些问题。

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

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

    【讨论】:

    • 所以我必须在设置占位符后在代码中设置每个文本字段,而不是通过扩展或界面构建器来设置?
    • 或者你添加一些其他的自定义属性(或函数)到你的UITextField 扩展,让你设置占位符文本,同时保留已经设置的任何颜色。然后将self.nameTextField.placeholder = username 更改为self.nameTextField.myPlaceholder = username
    【解决方案2】:

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

    【讨论】:

    • 这是对您问题的回答还是该问题的其他详细信息?
    • 请注意,这会使您的 placeHolderColor 属性毫无意义。
    • 是的,我删除了扩展和运行时属性,因为它毫无意义
    猜你喜欢
    • 2013-09-12
    • 2014-01-31
    • 2012-05-16
    • 2012-04-12
    • 2010-11-23
    • 1970-01-01
    • 2019-04-04
    • 1970-01-01
    • 2014-06-03
    相关资源
    最近更新 更多