Search code examples
iosswiftkeyboard

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


I'm creating a login system and I don't want spaces to be allowed in the username field. Instead of check and validating the field, I want to prevent spaces from being added.

So, every time the user presses the spacebar, nothing should happen. How can I do that? I've seen Instagram do this.

This is my code so far:

import UIKit

class ViewController: UIViewController, UITextFieldDelegate {

    @IBOutlet weak var signUp: UIBarButtonItem!
    @IBOutlet weak var navBar: UINavigationBar!
    @IBOutlet weak var UsernameText: UITextField!


    override func viewDidLoad() {
        super.viewDidLoad()

             self.navigationController?.navigationBar.clipsToBounds = true
        UsernameText.attributedPlaceholder = NSAttributedString(string:"TypeYourUsername",
            attributes:[NSForegroundColorAttributeName: UIColor.whiteColor()])

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

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    override func viewWillAppear(animated: Bool) {
        UsernameText.becomeFirstResponder()
    }


    override func prefersStatusBarHidden() -> Bool {
        return true
    }
}

Solution

  • 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.