F. Suyuti F. Suyuti - 5 months ago 33
Swift Question

SWIFT: Extension for UITextField that doesn't accept whitespace as input

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?

Answer

Actually this is quite simple, just subclass UITextField, add delegate to it, and implement the shouldChangeTextInRange there.

class BackspaceAcceptedTextField: 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
    }
  }
}