在用户完成输入并按下 return 后,如何在带有 textField 的 UIAlertController 中触发 UIAlertAction? [IOS-swift]

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

我有一个包含文本字段和两个操作的警报:保存和取消。用户在 textField 中输入内容后,我希望在用户按下键盘上的 return 时触发保存操作。我如何在 swift 5 中执行此操作?

我的代码附在下面。

@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)
    }

将委托添加到 UITextField

textField.delegate = self

并在键盘

中按下return键时使用以下委托方法
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
}