How do I get the return key to perform the same action as a button press in Swift?

Make sure your class extends the UITextFieldDelegate protocol

SomeViewControllerClass : UIViewController, UITextFieldDelegate

You can perform action as follows:

override func viewDidLoad() {
    super.viewDidLoad()

    self.textField.delegate = self
}

func textFieldShouldReturn(textField: UITextField) -> Bool {

    //textField code

    textField.resignFirstResponder()  //if desired
    performAction()
    return true
}

func performAction() {   
    //action events
}

UPDATE

If your deployment target is iOS 9.0 or later, you can connect the “Primary Action Triggered” event of your text field to an action, like this:

connecting primary action triggered event

ORIGINAL

Make your view controller adopt the UITextFieldDelegate protocol.

Set your text field's delegate to your view controller.

Implement textFieldShouldReturn: to call your action.


Swift 4.2 :

Other approach for the textfield created programmatically and doesn't need delegate :

     MyTextField.addTarget(self, action: #selector(MyTextFielAction)
                               , for: UIControl.Event.primaryActionTriggered)

And then perform your action like below :

    func MyTextFielAction(textField: UITextField) {
       //YOUR CODE can perform same action as your UIButton
    }

Tags:

Xcode

Swift

Ios8