【问题标题】:Change placeholder text color on swift快速更改占位符文本颜色
【发布时间】:2014-12-29 04:25:31
【问题描述】:

如何通过 Swift 更改 UITextField 的占位符文本颜色?我似乎无法访问占位符属性。谢谢

【问题讨论】:

    标签: ios swift


    【解决方案1】:

    您可以使用 属性字符串 设置占位符文本。将颜色设置为attributes 属性。

       textField.attributedPlaceholder = NSAttributedString(string:"placeholder text",
       attributes:[NSForegroundColorAttributeName: UIColor.yellowColor()])
    

    斯威夫特 5

    textField.attributedPlaceholder = NSAttributedString(string:"placeholder text", attributes:[NSAttributedString.Key.foregroundColor: UIColor.yellow])
    

    【讨论】:

      【解决方案2】:

      点击+按钮并添加一个新的运行时属性:_placeholderLabel.textColor

      运行您的应用程序。

      【讨论】:

        【解决方案3】:

        在 swift 中,您可以使用代码更改占位符颜色,

         name_textField .setValue(UIColor.redColor(), forKeyPath: "_placeholderLabel.textColor")
        

        【讨论】:

        • 这不是一个好的解决方案。使用这种方法,您无法保证 App Store 的批准,并且可能会在未来的 iOS 版本中悄然中断。
        • 我认为您应该建议任何故障安全方法来实现这一点,而不是投票。如果它仍然在最新版本中工作,它很可能会继续工作很长时间。并且不能保证 Apple 会删除或保留它。所以,如果它能让我们得到想要的结果,为什么还要犹豫呢?顺便说一句,在说“这不是一个好的解决方案”之后,请提供您的出色解决方案。
        • 我已经在 Swift 2.2 中尝试过,但它无法正常工作并出现错误。 self.txtFldFirstName.setValue(UIColor(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0), forKey: "_placeholderLabel.textColor") 出现此类错误与键 _placeholderLabel 的键值编码不兼容.textColor
        • @GautamSareriya:我在 swift 3 中也遇到此代码崩溃,您有任何更新吗?
        【解决方案4】:

        您可以创建Textfield的子类,并可以覆盖textfield的DrawRect函数。 通过创建子类,您可以轻松地为每个文本字段设置它。

        class CustomTextfield :UITextField {
         override func drawRect(rect: CGRect) {
        self.attributedPlaceholder = NSAttributedString(string:self.placeholder != nil ? self.placeholder! : "", attributes:[NSForegroundColorAttributeName: UIColor.grayColor()])
        } }
        

        【讨论】:

          【解决方案5】:

          斯威夫特 4:

          emailTextField.attributedPlaceholder = NSAttributedString(string: "e-mail", attributes: [NSAttributedStringKey.foregroundColor : UIColor.white])
          

          【讨论】:

            【解决方案6】:

            斯威夫特 5

              text.attributedPlaceholder = NSAttributedString(string: "your holder text", attributes: [NSAttributedString.Key.foregroundColor : textHolderColor])
            

            【讨论】:

              猜你喜欢
              • 2017-05-18
              • 2013-02-04
              • 2010-11-23
              • 1970-01-01
              • 2019-12-09
              • 2014-11-22
              • 2023-02-06
              • 2017-10-03
              相关资源
              最近更新 更多