UITextField - capture return button event

71,190

Solution 1

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

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

enter image description here

Solution 2

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.

Solution 3

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()
}

Solution 4

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

Solution 5

Swift 5

textField.addTarget(textField, action: #selector(resignFirstResponder), for: .editingDidEndOnExit)
Share:
71,190

Related videos on Youtube

Ilya Suzdalnitski
Author by

Ilya Suzdalnitski

Full-stack engineer with a focus on delivering reliable and maintainable software. I have a strong preference for functional programming and believe that it is the most important aspect of producing quality software. Passionate about continuous improvement, and always eager to learn and apply new technology.

Updated on July 08, 2022

Comments

  • Ilya Suzdalnitski
    Ilya Suzdalnitski almost 2 years

    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.

  • zekel
    zekel about 13 years
    Make sure your view controller is set as the textfield's delegate.
  • alex-i
    alex-i almost 9 years
    I just want to point out that UIControlEventEditingDidEndOnExit event gets sent only if textFieldShouldReturn: delegate method returns YES (without prior resigning the text field).
  • mxcl
    mxcl almost 9 years
    You don't have to implement delegation. But maybe if you do you have to return YES for this method.
  • haxpor
    haxpor over 8 years
    Thank you. For me I set the delegate via self.yourTextField.delegate = self;. Even multiple of text fields also work.
  • Blake Lockley
    Blake Lockley about 6 years
    @Praxiteles This can now be done in storyboard without requiring delegation please check answer below.