Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 257
F. Suyuti Avatar asked Nov 19 '25 19:11

F. Suyuti


1 Answers

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
    }
  }
}
like image 87
unknowncoder Avatar answered Nov 22 '25 08:11

unknowncoder



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!