Amit Kalra
Amit Kalra

Reputation: 4113

Resign Keyboard when Enter Key is Pressed in Swift

I have tried the following code but for some reason whenever I press the enter key on the keyboard, the keyboard does not resign. Why doesn't this work?

func trynaReturnKeyboard -> Bool {

       firstTextField.resignFirstResponder()
       secondTextField.resignFirstResponder()
       return true

}

Upvotes: 1

Views: 3803

Answers (4)

Kyle Browning
Kyle Browning

Reputation: 5382

Swift 4 iOS SDK 11.0

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

Upvotes: 1

iDhaval
iDhaval

Reputation: 3205

  1. you have to extend UITextFieldDelegate
  2. give delegate to UITextField
  3. Define textFieldShouldReturn

Example

firstTextField.delegate = self
firstTextField.returnKeyType = UIReturnKeyType.Done

secondTextField.delegate = self
secondTextField.returnKeyType = UIReturnKeyType.Done

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

Upvotes: 1

Vivek Molkar
Vivek Molkar

Reputation: 3960

You should override UITextFieldDelegate method textFieldShouldReturn to return true. Add the following code and assign your ViewController as delegate of the textfield.

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

Upvotes: 0

Fatti Khan
Fatti Khan

Reputation: 1553

Use the textFieldDelegate and then use this code and assign the delegate self to you textfields in Viewdidload as

class yourClass: UIViewController , UITextFieldDelegate {

func viewDidLoad(){

  super.viewDidLoad()
  firstTextField.delegate = self
  secondTextField.delegate = self
}

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

Upvotes: 6

Related Questions