user3029790
user3029790

Reputation: 321

How do you trigger a UIAlertAction in a UIAlertController with textField after users finish input and press return? [IOS-swift]

I have an alert that has a textField and two actions: save and cancel. After a user put something in the textField, I want the save action to be triggered when the user presses return on the keyboard. How do I do this in swift 5?

My code is attached below.

@IBAction func addNewCellButton(_ sender: Any) {
        let alert = UIAlertController(title: "Title", message: "msg", preferredStyle: .alert)
        alert.addTextField { (textField) in
            textField.placeholder = "enter something"
            textField.textColor = .black
            textField.backgroundColor = .white
        }
        let save = UIAlertAction(title: "Save", style: .default) { (alertAction) in
             print("Save pressed, text entered is ", textField.text!)
        }
        alert.addAction(save)
        let cancel = UIAlertAction(title: "Cancel", style: .default) { (alertAction) in
        }
        alert.addAction(cancel)
        self.present(alert, animated: true, completion: nil)
    }

Upvotes: 0

Views: 146

Answers (1)

Harish
Harish

Reputation: 2512

Add delegate to UITextField

textField.delegate = self

and use the following delegate method when return key pressed in keyboard

func textFieldShouldReturn(textField: UITextField) -> Bool {
    // Do your stuff here to get the text or whatever you need.
    // In your case Dismiss the Alert View Controller
    print("Save pressed, text entered is ", textField.text!)
    self.dismissViewControllerAnimated(true, completion: nil)
    return true
}

Upvotes: 1

Related Questions