3

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?

F. Suyuti
  • 327
  • 3
  • 18

2 Answers2

1

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
    }
  }
}
unknowncoder
  • 132
  • 1
  • 10
  • This has one serious flaw - no other validation is supported. What if you need multiple `BackspaceAcceptedTextField` (strange name for what this does BTW) on a single view controller and each one should accept only a certain number (but different) of characters? – rmaddy Jun 14 '16 at 02:40
  • Ah sorry for that name, i just copy from my last project for this answer, lol, let me change that name. The question just simple, F. Suyuti want a `UITextField` that didn't accept white space and he don't want implement it on every `viewController`. If you need more filter on some `viewController` then you need to ovveride it. – unknowncoder Jun 16 '16 at 02:48
0

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

Community
  • 1
  • 1
Santosh
  • 2,900
  • 1
  • 16
  • 16