如何在不同类中使用UIAlert获取文本字段值?斯威夫特

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

我使文件包含不同种类的通用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")
        })
    }
swift alert uialertview
1个回答
0
投票

您也可以在方法中添加另一个参数以通过警报控制器:

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)")
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.