Как вы запускаете UIAlertAction в UIAlertController с textField после того, как пользователи закончили ввод sh и нажали return? [IOS -swift] - PullRequest
0 голосов
/ 29 февраля 2020

У меня есть предупреждение с textField и двумя действиями: сохранить и отменить. После того, как пользователь поместил что-то в textField, я хочу, чтобы действие сохранения было запущено, когда пользователь нажимает клавишу возврата на клавиатуре. Как мне это сделать в 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)
    }

1 Ответ

1 голос
/ 29 февраля 2020

Добавьте делегата к 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
}
...