How do I bind an action to the Go button of the keyboard in iOS ?
Asked
Active
Viewed 2.0k times
20
2 Answers
42
Objective-C
Assuming you're using a UITextField, you could use the <UITextFieldDelegate>
method textFieldShouldReturn
.
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
[textField resignFirstResponder]; // Dismiss the keyboard.
// Execute any additional code
return YES;
}
Don't forget to assign the class you put this code in as the text field's delegate.
self.someTextField.delegate = self;
Or if you'd prefer to use UIControlEvents, you can do the following
[someTextField addTarget:self action:@selector(textFieldDidReturn:) forControlEvents:UIControlEventEditingDidEndOnExit];
- (void)textFieldDidReturn:(UITextField *)textField
{
// Execute additional code
}
See @Wojtek Rutkowski's answer to see how to do this in Interface Builder.
Swift
UITextFieldDelegate
class SomeViewController: UIViewController, UITextFieldDelegate {
let someTextField = UITextField()
override func viewDidLoad() {
super.viewDidLoad()
someTextField.delegate = self
}
func textFieldShouldReturn(textField: UITextField) -> Bool {
textField.resignFirstResponder() // Dismiss the keyboard
// Execute additional code
return true
}
}
UIControlEvents
class SomeViewController: UIViewController {
let someTextField = UITextField()
override func viewDidLoad() {
super.viewDidLoad()
// Action argument can be Selector("textFieldDidReturn:") or "textFieldDidReturn:"
someTextField.addTarget(self, action: "textFieldDidReturn:", forControlEvents: .EditingDidEndOnExit)
}
func textFieldDidReturn(textField: UITextField!) {
textField.resignFirstResponder()
// Execute additional code
}
}

Community
- 1
- 1

Mick MacCallum
- 129,200
- 40
- 280
- 281
30
You can connect UITextFiled
event Did End On Exit
in Connections Inspector
. It is triggered after tapping Go
/ Return
/ whatever you choose as Return Key
in Attributes Inspector
.

Wojciech Rutkowski
- 11,299
- 2
- 18
- 22
-
The answer from @0x7fffffff is correct and normally you also have to include some of the delegates so the `UITextField` works correctly. So better stay on the delegates included in code instead working with `UIInterfaceBuilder` too for this little function! – Alex Cio Jun 10 '15 at 11:24