Search code examples
iosobjective-cuitextfielduikeyboarduitextfielddelegate

Action of the "Go" button of the ios keyboard


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


Solution

  • 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
        }
    }