我使文件包含不同种类的通用UIAlert
代码,因此我可以重复使用它们。我的问题是如何从另一个班级获得textfield value
?到目前为止,我发现的所有答案都被编码在同一个类中,而我不希望这样。谢谢。
UIAlert文件
func alertVerify(title: String, message: String, sender: UIViewController, verifyActionCompletionHandler: ((UIAlertAction) -> Void)? = nil, resendActionCompletionHandler: ((UIAlertAction) -> Void)? = nil) {
let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
let verifyAction = UIAlertAction(title: "Verify", style: .default, handler: verifyActionCompletionHandler)
alert.addAction(verifyAction)
let resendAction = UIAlertAction(title: "Resend", style: .default, handler: resendActionCompletionHandler)
alert.addAction(resendAction)
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
alert.addAction(cancelAction)
alert.addTextField(configurationHandler: { textField in
textField.placeholder = "Verification code"
})
DispatchQueue.main.async(execute: {
sender.present(alert, animated: true)
})
}
ViewController
func verifyEmail() {
guard let email = inputTextField.text else {
return
}
alertVerify(title: "Email Verification Code", message: "Enter the verification code we send in your updated email adress.", sender: self, verifyActionCompletionHandler: { UIAction in
if let inputCode = alert.textFields?.first?.text { //error: unresolved identifier 'alert'
print("Verification code: \(inputCode)")
//Do something
}
}, resendActionCompletionHandler: { UIAction in
self.updateData(updateItem: "email", updateData: ["email": email], endpoint: "info")
})
}
您也可以在方法中添加另一个参数以通过警报控制器:
func alertVerify(title: String, message: String, sender: UIViewController, alert: UIAlertController, verify: ((UIAlertAction) -> Void)? = nil, resend: ((UIAlertAction) -> Void)? = nil) {
alert.title = title
alert.message = message
alert.addTextField { textField in
textField.placeholder = "Verification code"
}
alert.addAction(.init(title: "Verify", style: .default, handler: verify))
alert.addAction(.init(title: "Resend", style: .default, handler: resend))
alert.addAction(.init(title: "Cancel", style: .cancel))
DispatchQueue.main.async {
sender.present(alert, animated: true)
}
}
然后,当您调用方法时,将警报控制器的实例传递给它:
func verifyEmail() {
let alert = UIAlertController.init(title: nil, message: nil, preferredStyle: .alert)
alertVerify(title: "Email Verification Code", message: "Enter the verification code we send in your updated email adress.", sender: self, alert: alert) { action in
let inputCode = alert.textFields![0].text!
print("Verification code: \(inputCode)")
}
}