user3349374
user3349374

Reputation:

How to hide keyboard when return key is hit - Swift

Trying to hide the iOS keyboard when the return key is hit, but instead it halts and gives me the error seen in the image. Here's the code I'm using:

@IBOutlet weak var scoreText: UITextField!

func textFieldShouldReturn(_ scoreText: UITextField) -> Bool {
    self.view.endEditing(true)
    return false
}

enter image description here

Upvotes: 13

Views: 28294

Answers (3)

Enamul Haque
Enamul Haque

Reputation: 5053

In swift 4 or 5 , You can use like :

  1. create a project
  2. add UITextField & connect to ViewController
  3. implement UITextFieldDelegate to ViewController
  4. Initialize the UITextField delegate
  5. Add textFieldShouldReturn method in ViewController
  6. Here is full code

    class ViewController: UIViewController,UITextFieldDelegate {
    
     //Connect to text field
     @IBOutlet weak var scoreText: UITextField!
    
     override func viewDidLoad() {
       super.viewDidLoad()
    
        //must initialize delegate
        scoreText.delegate = self
      }
    
     //add method
     func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        textField.resignFirstResponder()
        return true
     }  
    
    }
    

Upvotes: 1

Mr. Xcoder
Mr. Xcoder

Reputation: 4795

Your problem is that you didn't delegate a textField in order to use that method. First, your class must include the UITextFieldDelegate protocol:

class yourClass: UIViewController, UITextFieldDelegate { ... }

And in the viewDidLoad() method, add this as well:

scoreText.delegate = self

And then you have to change this:

func textFieldShouldReturn(_ scoreText: UITextField) -> Bool {
    self.view.endEditing(true)
    return false
}

to this:

func textFieldShouldReturn(_ scoreText: UITextField) -> Bool {
    self.view.endEditing(true)
    return true
}

Final code:

class yourClass: UIViewController, UITextFieldDelegate {

    @IBOutlet weak var scoreText: UITextField!

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

    func textFieldShouldReturn(_ scoreText: UITextField) -> Bool {
        self.view.endEditing()
        return true
    }
}

If this is not working, the problem is not the textFieldShouldReturn() function. Please check your outlet connections.

Upvotes: 36

Mochi
Mochi

Reputation: 1117

Try this

func textFieldShouldReturn(_ textField: UITextField) -> Bool {
    textField.resignFirstResponder()
    return true
}

Upvotes: 5

Related Questions