Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UITextField - capture return button event

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.

like image 808
Ilya Suzdalnitski Avatar asked Jun 10 '09 16:06

Ilya Suzdalnitski


3 Answers

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

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

enter image description here

like image 74
Ilya Suzdalnitski Avatar answered Oct 04 '22 04:10

Ilya Suzdalnitski


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.

like image 32
mxcl Avatar answered Oct 04 '22 03:10

mxcl


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()
}
like image 20
drpawelo Avatar answered Oct 04 '22 04:10

drpawelo