在用户完成输入并按return键后,如何在带有textField的UIAlertController中触发UIAlertAction?[IOS swift]
我有一个警报,它有一个文本字段和两个操作:保存和取消。用户在文本字段中输入内容后,我希望在用户按键盘上的return键时触发save操作。如何在swift 5中执行此操作 我的代码附在下面在用户完成输入并按return键后,如何在带有textField的UIAlertController中触发UIAlertAction?[IOS swift],ios,swift,uialertcontroller,uialertaction,Ios,Swift,Uialertcontroller,Uialertaction,我有一个警报,它有一个文本字段和两个操作:保存和取消。用户在文本字段中输入内容后,我希望在用户按键盘上的return键时触发save操作。如何在swift 5中执行此操作 我的代码附在下面 @IBAction func addNewCellButton(_ sender: Any) { let alert = UIAlertController(title: "Title", message: "msg", preferredStyle: .alert) aler
@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
并在键盘上按返回
键时使用以下委托方法
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
}