Ios SwiftUI:UIAlertController';在UIAlertAction中,s文本字段没有响应

Ios SwiftUI:UIAlertController';在UIAlertAction中,s文本字段没有响应,ios,uikit,swiftui,uialertcontroller,uialertaction,Ios,Uikit,Swiftui,Uialertcontroller,Uialertaction,我需要使用UIAlertContoller,因为SwiftUI的Alert不支持TextField 由于各种原因(可访问性、DynamicType、暗模式支持等),我不能使用自定义创建的AlertView 基本思想是,SwiftUI的警报必须保持TextField&输入的文本必须反射回来以供使用。 我根据UIViewControllerRepresentable创建了一个SwiftUI视图,以下是工作代码 struct AlertControl: UIViewControllerRepresen

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

由于各种原因(可访问性、DynamicType、暗模式支持等),我不能使用自定义创建的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")


编辑:
cancelAction
submitAction
不会在点击这些字段时触发。

这里是解决方案的完整演示模块。使用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)
        }
    }
}
struct AlertControl:UIViewControllerRepresentable{
@绑定变量textString:String
@绑定变量显示:Bool
变量标题:字符串
var消息:字符串
func makeUIViewController(上下文:UIViewControllerRepresentableContext)->UIViewController{
返回UIViewController()//保持器控制器-需要显示警报
}
func updateUIViewController(viewController:UIViewController,上下文:UIViewControllerRepresentableContext){
guard context.coordinator.alert==nil else{return}
如果自我表现{
let alert=UIAlertController(标题:标题,消息:消息,首选样式:。警报)
context.coordinator.alert=警报
alert.addTextField{textField in
textField.placeholder=“输入一些文本”
textField.text=self.textString//Bool{
如果让text=textField.text作为NSString{
self.control.textString=text.replacingCharacters(在:范围内,带:字符串)
}否则{
self.control.textString=“”
}
返回真值
}
}
}
//警报控制器的演示视图
结构DemoAlertControl:视图{
@国家私有变量text=“”
@状态私有变量showAlert=false
var body:一些观点{
VStack{
按钮(“警报”){self.showAlert=true}
.background(AlertControl)(文本字符串:self.$text,show:self.$showAlert,
标题:“标题在这里”,信息:“信息在这里”))
文本(self.Text)
}
}
}

感谢您的响应,但这并不能解决实际问题。
取消操作
提交操作
在点击这些按钮时不会触发。感谢@Asperi,这正按预期工作,但有时屏幕冻结&我在控制台中看到以下警告。
2020-04-17 22:11:27.121106+0530 SwiftUI警报控制器[98884:3206838]警告:尝试呈现已呈现的内容(null)
总的来说,它解决了问题。再次感谢。@Nasir,在已经显示的警报中添加了守卫,以避免意外刷新。谢谢@Asperi,但我看不出coordinator中的守卫语句和警报实例的目的是什么,即使有上述更改,也会出现警告。似乎警报控制器已显示,但它从未关闭d、 在某个地方,我们要求解除呈现的警报。让我知道你的想法,我正在努力,一旦得出任何结论,我会更新。顺便说一句,谢谢你的努力。:@Nasir,你说的“永不解除”是什么意思?当我测试和演示时,警报按预期工作,并在任何按钮点击时解除。您是否使用不同的Xcode版本或条件?需要
保护
,因为我们不控制SwiftUI在representable中调用update的时间,所以为了避免在警报已显示时发生冲突,我添加了保护并修改代码以存储警报。正如我使用在控制台中,我不再收到任何警告。
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)
        }
    }
}