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

4

由于 SwiftUI 的 Alert 不支持 TextField,我需要使用 UIAlertContoller

由于各种原因(包括可访问性、动态类型、深色模式支持等),我不能使用自定义创建的 AlertView。

基本思路是,SwiftUI 的警报必须包含 TextField,并且输入的文本必须反映回用途。

我通过符合 UIViewControllerRepresentable 来创建了一个 SwiftUI 视图,下面是可工作的代码。

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

编辑: 点击这些字段时,cancelActionsubmitAction不会被触发。
2个回答

5
这是一个完整的演示模块,适用于IT技术解决方案。测试过使用Xcode 11.4 / iOS 13.4。
请参见内联的重要注释。
(附带html标签)

demo

struct AlertControl: UIViewControllerRepresentable {

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

    var title: String
    var message: String

    func makeUIViewController(context: UIViewControllerRepresentableContext<AlertControl>) -> UIViewController {
        return UIViewController() // holder controller - required to present alert
    }

    func updateUIViewController(_ viewController: UIViewController, context: UIViewControllerRepresentableContext<AlertControl>) {
        guard context.coordinator.alert == nil else { return }
        if self.show {
            let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
            context.coordinator.alert = alert

            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
            }
            alert.addAction(UIAlertAction(title: "cancel", style: .destructive) { _ in
                // your action here
            })
            alert.addAction(UIAlertAction(title: "Submit", style: .default) { _ in
                // your action here
            })

            DispatchQueue.main.async { // must be async !!
                viewController.present(alert, animated: true, completion: {
                    self.show = false  // hide holder after alert dismiss
                    context.coordinator.alert = nil
                })
            }
        }
    }

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

    class Coordinator: NSObject, UITextFieldDelegate {
        var alert: UIAlertController?
        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 as NSString? {
                self.control.textString = text.replacingCharacters(in: range, with: string)
            } else {
                self.control.textString = ""
            }
            return true
        }
    }
}

// Demo view for Alert Controll
struct DemoAlertControl: View {
    @State private var text = ""
    @State private var showAlert = false

    var body: some View {
        VStack {
            Button("Alert") { self.showAlert = true }
                .background(AlertControl(textString: self.$text, show: self.$showAlert,
                         title: "Title goes here", message: "Message goes here"))
            Text(self.text)
        }
    }
}

谢谢您的回复,但它并没有解决实际问题。当点击这些按钮时,cancelActionsubmitAction不会触发。 - Nasir
谢谢@Asperi,这个工作正常,但有时屏幕会冻结,我在控制台中看到以下警告。2020-04-17 22:11:27.121106+0530 SwiftUI Alert Controller[98884:3206838] Warning: Attempt to present <UIAlertController: 0x7f8cdd87e000> on <UIViewController: 0x7f8cdd704fd0> which is already presenting (null)总的来说,它解决了问题。再次感谢。 - Nasir
1
@Nasir,为了避免意外刷新,已经显示的警报添加了守卫。 - Asperi
@Nasir,你说的“never dismissed”是什么意思?我测试和演示了警报功能,它可以按预期工作,并在任何按钮点击时被解除。你使用不同的Xcode版本或条件吗?guard是必需的,因为我们无法控制SwiftUI何时调用可表示性中的更新,所以为了避免冲突,如果警报已经显示,我添加了guard并修改了代码来存储警报。当我使用这种方法进行测试时,我不再收到控制台中的任何警告。 - Asperi
我在iOS15中尝试了解决方案,但shouldChangeCharactersIn没有被调用:( - anoop4real
显示剩余2条评论

1
如果您不需要支持之前的版本,那么在iOS16中,您实际上可以非常直接地在.alert()中使用TextField
struct ContentView: View {
    @State private var isShowingAlert = false
    @State private var alertInput = "Hello, world!"
    var body: some View {
        VStack {
            Text(alertInput)
            Text("Alert Message \(Image(systemName: "exclamationmark.triangle.fill"))")
            Button("Show alert", action: { isShowingAlert = true })
        }
        .padding()
        .alert("Alert message...", isPresented: $isShowingAlert) {
            TextField("", text: $alertInput) // Works in iOS16, but is ignored in iOS15
            Text("Alert Message \(Image(systemName: "exclamationmark.triangle.fill"))") // `Image` concatenation won't work
            Button("OK", action: { })
        }
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接