Reputation: 327
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?
Upvotes: 3
Views: 1197
Reputation: 132
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
}
}
}
Upvotes: 1
Reputation: 2914
Swift allows to extend the protocols
as well. You can make an extension UITextFieldDelegate
and implement your custom code in that method. But there are some limitations, check this answer, it will help you swift 2.0 - UITextFieldDelegate protocol extension not working
Upvotes: 0