SwiftUI:UIAlertController的textField在UIAlertAction中没有响应

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

我需要使用UIAlertContoller,因为SwiftUI的Alert不支持TextField

由于各种原因(可访问性,DynamicType,暗模式支持等,我不能使用自定义创建的AlertView。

基本思想是,SwiftUI的警报必须包含TextField且输入的文本必须反射回来以供使用。

我通过遵循view来创建SwiftUI UIViewControllerRepresentable,以下是工作代码。

struct AlertControl: UIViewControllerRepresentable {

    typealias UIViewControllerType = UIAlertController

    @Binding var textString: String
    @Binding var show: Bool

    var title: String
    var message: String

    func makeUIViewController(context: UIViewControllerRepresentableContext<AlertControl>) -> UIAlertController {

        let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)

        alert.addTextField { textField in
            textField.placeholder = "Enter some text"
        }

        let cancelAction = UIAlertAction(title: "cancel", style: .destructive) { (action) in
            self.show = false
        }

        let submitAction = UIAlertAction(title: "Submit", style: .default) { (action) in
            self.show = false
        }

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

        return alert
    }

    func updateUIViewController(_ uiViewController: UIAlertController, context: UIViewControllerRepresentableContext<AlertControl>) {

    }

    func makeCoordinator() -> AlertControl.Coordinator {
        Coordinator(self)
    }

    class Coordinator: NSObject, UITextFieldDelegate {

        var control: AlertControl

        init(_ control: AlertControl) {
            self.control = control
        }

        func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
            if let text = textField.text {
                self.control.textString = text
            }

            return true
        }
    }
}

// SwiftUI View in some content view
 AlertControl(textString: self.$text,
                             show: self.$showAlert,
                             title: "Title goes here",
                             message: "Message goes here")

问题:

被点击时,警报措施中没有任何活动。我检查了断点,但它从未击中过。

即使UITextFieldDelegate的功能也不会被点击。

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool
ios uikit swiftui uialertcontroller uialertaction
1个回答
0
投票

您忘记了在文本字段配置期间添加委托,因此要修复

alert.addTextField { textField in
    textField.placeholder = "Enter some text"
    textField.text = self.textString            // << initial value if any
    textField.delegate = context.coordinator    // << use coordinator as delegate
}
© www.soinside.com 2019 - 2024. All rights reserved.