Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Action of the "Go" button of the ios keyboard

How do I bind an action to the Go button of the keyboard in iOS ?

like image 887
Alexis Avatar asked Oct 25 '12 09:10

Alexis


2 Answers

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
    }
}
like image 195
Mick MacCallum Avatar answered Nov 18 '22 08:11

Mick MacCallum


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.

Connections Inspector

like image 23
Wojciech Rutkowski Avatar answered Nov 18 '22 08:11

Wojciech Rutkowski