I know shouldChangeTextInRange method on UITextFieldDelegate can filter input on UITextField, it's ok if i only need to filter one UITextField. Now my problem is i have lot of UITextField that need to filter whitespace. And i don't want to implement shouldChangeTextInRange on every UIViewController that have UITextField in it. Is there anyway to make extension of the UITextField or other?
Actually this is quite simple, just subclass UITextField, add delegate to it, and implement the shouldChangeTextInRange there.
class CustomTextField: UITextField, UITextFieldDelegate {
override func awakeFromNib() {
super.awakeFromNib()
delegate = self
}
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
if (string.rangeOfCharacterFromSet(.whitespaceCharacterSet()) != nil) {
return false
} else {
return true
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With