问题
How do I bind an action to the Go button of the keyboard in iOS ?
回答1:
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
}
}
回答2:
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
.
来源:https://stackoverflow.com/questions/13065868/action-of-the-go-button-of-the-ios-keyboard