108

How can I detect when a user pressed "return" keyboard button while editing UITextField? I need to do this in order to dismiss keyboard when user pressed the "return" button.

Thanks.

TheNeil
  • 3,321
  • 2
  • 27
  • 52
Ilya Suzdalnitski
  • 52,598
  • 51
  • 134
  • 168

7 Answers7

218
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [textField resignFirstResponder];
    return NO;
}

Don't forget to set the delegate in storyboard...

enter image description here

Fattie
  • 27,874
  • 70
  • 431
  • 719
Ilya Suzdalnitski
  • 52,598
  • 51
  • 134
  • 168
54

Delegation is not required, here's a one-liner:

- (void)viewDidLoad {
    [textField addTarget:textField
                  action:@selector(resignFirstResponder)
        forControlEvents:UIControlEventEditingDidEndOnExit];
}

Sadly you can't directly do this in your Storyboard (you can't connect actions to the control that emits them in Storyboard), but you could do it via an intermediary action.

mxcl
  • 26,392
  • 12
  • 99
  • 98
  • 1
    I just want to point out that `UIControlEventEditingDidEndOnExit` event gets sent only if `textFieldShouldReturn:` delegate method returns YES (without prior resigning the text field). – alex-i Jul 26 '15 at 12:20
  • You don't *have* to implement delegation. But maybe if you do you have to return `YES` for this method. – mxcl Jul 27 '15 at 23:30
  • You can also use primaryActionTriggered event if you don't want to dismiss the keyboard. – Nikita Tepliakov Mar 16 '23 at 19:40
11

SWIFT 3.0

override open func viewDidLoad() {
    super.viewDidLoad()    
    textField.addTarget(self, action: #selector(enterPressed), for: .editingDidEndOnExit)
}

in enterPressed() function put all behaviours you're after

func enterPressed(){
    //do something with typed text if needed
    textField.resignFirstResponder()
}
drpawelo
  • 2,348
  • 23
  • 17
11

You can now do this is storyboard using the sent event 'Did End On Exit'.

In your view controller subclass:

 @IBAction func textFieldDidEndOnExit(textField: UITextField) {
    textField.resignFirstResponder()
}

In your storyboard for the desired textfield:

enter image description here

Blake Lockley
  • 2,931
  • 1
  • 17
  • 30
7

Swift 5

textField.addTarget(textField, action: #selector(resignFirstResponder), for: .editingDidEndOnExit)
Ted
  • 22,696
  • 11
  • 95
  • 109
5

Swift version using UITextFieldDelegate :

func textFieldShouldReturn(_ textField: UITextField) -> Bool {
    resignFirstResponder()
    return false
}
Leo Dabus
  • 229,809
  • 59
  • 489
  • 571
-1
- (BOOL)textFieldShouldReturn:(UITextField *)txtField 
{
[txtField resignFirstResponder];
return NO;
}

When enter button is clicked then this delegate method is called.you can capture return button from this delegate method.