簡體   English   中英

如果我在 XIB 中設計了 textField,如何以編程方式更改 UItextField 的 placeHolder 文本

[英]How to change placeHolder text of UItextField programmatically if I have designed textField in XIB

我必須創建一個自定義類來設計XIB textField並在我的viewController多次重用它。 我想以編程方式更改每個占位符名稱。

創建子類為:

class CustomTextField: UITextField {

    override func awakeFromNib() {
        super.awakeFromNib()

    }

    func placeHolderColor(pColor: UIColor, pText: String) {

        self.attributedPlaceholder = NSAttributedString(string: pText,
                                                               attributes: [NSAttributedStringKey.foregroundColor: pColor])

    }
}

在您的文本字段自定義類中聲明一個字符串類型的開放變量。 訪問該變量以更改曾經實施的占位符名稱。

您可以通過以下兩種方式進行更改

1) yourTextField.placeholder = "some string"

2) yourTextField.attributedPlaceholder = NSAttributedString(string: "some string")

如果要更改占位符,可以使用以下代碼

yourTextField.attributedPlaceholder =
            NSAttributedString(string: "YourText", attributes: [NSForegroundColorAttributeName : UIColor.white])

嘗試制作自定義 uitextfield 類

@IBDesignable
class CustomTextField: UITextField {

    @IBInspectable var TFPlaceholder: String? {
        willSet {
            self.placeholder = newValue
        }
    }
}

在此處輸入圖片說明

祝你好運!! :)

快速> 5.0

 class CustomTextField: UITextField {

override func awakeFromNib() {
    super.awakeFromNib()

}

func placeHolderColor(pColor: UIColor, pText: String) {
          self.attributedPlaceholder = NSAttributedString(pText,
                attributes: [NSAttributedString.Key.foregroundColor: pColor])
   }
}

yourTextfield.attributedPlaceholder = NSAttributedString(string: "yourPlaceholderText")

這對我有用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM