SwiftUI:UIAlertController的textField在UIAlertAction中没有响应 [英] SwiftUI: UIAlertController's textField does not responding in UIAlertAction

查看:318
本文介绍了SwiftUI:UIAlertController的textField在UIAlertAction中没有响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I need to use UIAlertContoller, as SwiftUI's Alert does not support TextField.

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

I must not use Custom created AlertView, due to various reason(Accessibility, DynamicType, Dark Mode support etc).

基本思路是,SwiftUI的警报必须包含TextField&输入的文本必须回显以便使用.

Basic Idea is, SwiftUI's alert must hold TextField & entered text must be reflect back for usage.

我通过遵循UIViewControllerRepresentable的工作代码来创建了SwiftUI view.

I created a SwiftUI view by Conforming to UIViewControllerRepresentable following is working code.

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")

问题:

在点击警报操作"时没有任何活动.我检查了断点,但是它从来没有打到那里.

There is No activity in Alert Action when it is tapped. I put breakpoints to check, but it never hit there.

即使UITextFieldDelegate的功能也永远不会命中.

Even UITextFieldDelegate's function never hit.

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool

cancelActionsubmitAction不会在点击这些字段时触发.

cancelAction or submitAction does not triggers on tap of these fields.

推荐答案

此处是适用于解决方案的完整演示模块.使用Xcode 11.4/iOS 13.4进行了测试

Here is full demo module for solution that works. Tested with Xcode 11.4 / iOS 13.4

另请参见内嵌重要评论

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)
        }
    }
}

这篇关于SwiftUI:UIAlertController的textField在UIAlertAction中没有响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆