简体   繁体   中英

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

I have to make a custom class to design textField in XIB and reuse it multiple times in my viewController . I want to change each placeholder name programmatically.

Create subclass as:

class CustomTextField: UITextField {

    override func awakeFromNib() {
        super.awakeFromNib()

    }

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

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

    }
}

Declare an open variable of type string in your textfield custom class. Access that variable to change a placeholder name where ever implemented.

You can change by following two way

1) yourTextField.placeholder = "some string"

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

If you want to change the placeholder you can use the below code

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

try making a custom uitextfield class

@IBDesignable
class CustomTextField: UITextField {

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

在此处输入图片说明

Goodluck!! :)

for swift > 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")

This works for me.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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