How do I disable the "Space" Key on the keyboard in Swift?

In Swift 2.1

func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
    let whitespaceSet = NSCharacterSet.whitespaceCharacterSet()
    if let _ = string.rangeOfCharacterFromSet(whitespaceSet) {
       return false
       }
    return true
}

In Swift 2.0

func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
    let whitespaceSet = NSCharacterSet.whitespaceCharacterSet()
    let range = string.rangeOfCharacterFromSet(whitespaceSet)
    if let _ = range {
        return false
    }
    else {
        return true
    }
}

Yes you can do it. Override UITextField delegate method shouldChangeCharactersInRange. And in that method check for space character. If found than return false.

Note: Don't forget to set delegate for textfield.

func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
    if (string == " ") {
        return false
    }
    return true
}

Edit: More Code

class ViewController : UIViewController, UITextFieldDelegate {

    @IBOutlet weak var textField : UITextField!

    override func viewDidLoad() {
        super.viewDidLoad()
        textField.delegate = self
    }

    func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
        if (string == " ") {
          return false
        }
        return true
    }
}

Here textField object is an IBOutlet. It means that text field control is in storyboard and connected with this variable.


Swift 4.1/4.2/5.0/5.1/5.2

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