UITextField - capture return button event

IosIphoneCocoa TouchUitextfieldBackspace

Ios Problem Overview


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.

Ios Solutions


Solution 1 - Ios

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

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

enter image description here

Solution 2 - Ios

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 - Ios

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 - Ios

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 - Ios

Swift 5

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

Solution 6 - Ios

Swift version using UITextFieldDelegate :

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

Solution 7 - Ios

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionIlya SuzdalnitskiView Question on Stackoverflow
Solution 1 - IosIlya SuzdalnitskiView Answer on Stackoverflow
Solution 2 - IosmxclView Answer on Stackoverflow
Solution 3 - IosdrpaweloView Answer on Stackoverflow
Solution 4 - IosBlake LockleyView Answer on Stackoverflow
Solution 5 - IosTedView Answer on Stackoverflow
Solution 6 - IosLeo DabusView Answer on Stackoverflow
Solution 7 - IosMahendra VishwakarmaView Answer on Stackoverflow