使用模型中的 Alert class 访问 UIAlert TextField 中的文本

Access Text in UIAlertTextField using Alert class in Model

我在我的模型层中创建了一个警报 class 来显示简单的警报,效果很好。

class Alert {
    class func showBasic(title: String, message: String, vc: UIViewController) {
        let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
        alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
        vc.present(alert, animated: true)
    }
}

我正在尝试添加带有文本字段的第二个警报类型,并在视图控制器中提供文本字段的结果。我试过使用完成处理程序,但完成处理程序在警报显示完成时触发,而不是在实际输入文本时触发。如何捕获文本字段中的文本并在视图控制器中使用它?

class func withInput(title: String, message: String, vc: UIViewController, placeholder: String, btnTitle: String, complete: (_ result:String) -> Void) {
    let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
    alert.addTextField { (textField) in
        textField.placeholder = placeholder
    }
    alert.addAction(UIAlertAction(title: btnTitle, style: .default, handler: nil))
    vc.present(alert, animated: true)
    if let text = alert.textFields?[0].text {
        complete(text)
    }
}

完成处理程序需要进入 addAction 的完成处理程序

class func withInput(title: String, message: String, vc: UIViewController, placeholder: String, btnTitle: String, complete: @escaping (_ result:String) -> Void) {
    let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
    alert.addTextField { (textField) in
        textField.placeholder = placeholder
    }
    alert.addAction(UIAlertAction(title: btnTitle, style: .default, handler: { [weak alert] (_) in
        if let text = alert?.textFields?[0].text {
            complete(text)
        }
    }))
    vc.present(alert, animated: true)
}