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])
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.