仅当文本字段不为空时,如何在UIAlertController中检查和启用Action?

问题描述 投票:0回答:1

我试图弄清楚如何在用户输入一些文本之前保持禁用动作按钮的方式,此时用户将再次启用该按钮。我一直在搜索,有些人建议使用观察者?那是最好的方法吗?

干杯!

   @objc func addExercise() {
            var textField = UITextField()
            let alert = UIAlertController(title: "New Exercise", message: "Please name your Exercise...", preferredStyle: .alert)

            let cancelAction = UIAlertAction(title: "Cancel", style: .default) { (UIAlertAction) in
                alert.dismiss(animated: true, completion: nil)
            }

            let addAction = UIAlertAction(title: "Add Exercise", style: .default) { (UIAlertAction) in
                //Add Exercise to database.
                //Append exercise to selected workout object.
                let exercise = Exercises()
                exercise.exerciseName = textField.text!
                try! self.realm.write {
                    self.selectedWorkout?.exercise.append(exercise)
                    self.loadExercises()
                }
            }

            alert.addTextField { (alertTextField1) in
                alertTextField1.delegate = self
                alertTextField1.placeholder = "Bench Press"
                alertTextField1.text = textField.text
                textField = alertTextField1
            }

            alert.addAction(addAction)
            alert.addAction(cancelAction)

            present(alert, animated: true, completion: nil)

        }
swift xcode uitextfield uialertaction
1个回答
0
投票

使用通知是一种方法,但是要花很长时间,您可以使用简单的委托方法或文本字段的操作方法,如下所示,这更容易:]

    weak var buttonActionToEnable: UIAlertAction?

    alert.addTextField { (alertTextField1) in
                    alertTextField1.delegate = self
                    alertTextField1.placeholder = "Bench Press"
                    alertTextField1.text = textField.text

                    alertTextField1.addTarget(self, action: #selector(self.textFieldChanged), for: .editingChanged)
                }

    self.buttonActionToEnable = addAction
    addAction.isEnabled = false

    @objc func textFieldChanged(_ sender: Any) {

          self.buttonActionToEnable?.isEnabled = //textfield condition
    }
© www.soinside.com 2019 - 2024. All rights reserved.