Search code examples
iosswiftuitextfielduitextfielddelegate

How to prevent users from entering '#' and empty space(' ') in UITextfield - swift?


I am trying to prevent users from entering the characters '#' and empty spaces (' '). I have got as far as below (see code below) but not sure how to complete the rest ...

 class CreateTags: UIViewController, UITextFieldDelegate {

 /*** OUTLETS ***/
 @IBOutlet weak var inputTxtOutlet: UITextField!


 override func viewDidLoad() {
      self.inputTxtOutlet.delegate = self
 }

 func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    return true
  }

 }

Solution

  • You need o implement following delegate method (as you already implemented)

    Set delegate

    yourtextField.delegate = self
    

    Delegate method

    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    
        if string == "#" || string == " " {
            return false //disallow # and a space
        }
        return true
    
     }
    

    In another way you can do it as follow

    Create a constant that contains disallowed chars.

     let disallowedChars = ["#", " "] //add more chars as per your need
    

    In delegate method check those chars...

    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    
          if disallowedChars.contains(string) {
            return false
          }
    
          return true
    }