【发布时间】:2020-04-17 07:35:46
【问题描述】:
我需要使用UIAlertContoller,因为SwiftUI 的Alert 不支持TextField。
由于各种原因(可访问性、DynamicType、暗模式支持等),我不能使用自定义创建的 AlertView。
基本思想是,SwiftUI 的警报必须保持 TextField 并且输入的文本必须反射回来才能使用。
我通过遵循 UIViewControllerRepresentable 创建了一个 SwiftUI view 以下是工作代码。
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
编辑:cancelAction 或 submitAction 不会在点击这些字段时触发。
【问题讨论】:
标签: ios uikit swiftui uialertcontroller uialertaction