我正在尝试在SwiftUI View
中实现带有选中标记的操作表。我正在使用
UIViewControllerRepresentable
创建一个UIAlertController
struct WhatsAppAlertController: UIViewControllerRepresentable {
let viewModel: PropViewModel
func makeUIViewController(context: Context) -> UIAlertController {
let alert = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
let contactsNumbers = viewModel.contactsNumbers()
for number in contactsNumbers {
let action = UIAlertAction(
title: "\(number.value.stringValue)",
style: .default,
handler: { _ in
self.viewModel.openWhatsAppURL(withNumber: number.value.stringValue)
})
alert.addAction(action)
}
let cancel = UIAlertAction(title: L10n.cancel, style: .cancel, handler: nil)
alert.addAction(cancel)
return alert
}
func updateUIViewController(_ uiViewController: UIAlertController, context: Context) {
}
}
使用显示
.sheet(isPresented: $showWhatsAppActionSheet) {
WhatsAppAlertController(viewModel: self.viewModel)
}
我感觉是因为UIAlertController
是使用.sheet
呈现的
我的计划是使用action.setValue(true, forKey: "checked")
选中并记住所选的选项。
是否可以解决此问题?还是仅使用SwiftUI来实现选中标记?
答案 0 :(得分:0)
我的错误是没有创建一个持有人控制器,即一个UIViewController
来容纳UIAlertController
。演示文稿还应该使用.background()
而不是.sheet()
这是更新的代码:
struct WhatsappAlertController: UIViewControllerRepresentable {
@Binding var show: Bool
let viewModel: PropViewModel
func makeUIViewController(context: UIViewControllerRepresentableContext<WhatsappAlertController>) -> UIViewController {
return UIViewController() // holder controller - required to present alert
}
func updateUIViewController(_ uiViewController: UIViewController, context: UIViewControllerRepresentableContext<WhatsappAlertController>) {
if self.show {
let alert = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
let contactsNumbers = viewModel.contactsNumbers()
for number in contactsNumbers {
let action = UIAlertAction(
title: "\(number.value.stringValue)",
style: .default,
handler: { _ in
self.viewModel.openWhatsAppURL(withNumber: number.value.stringValue)
})
// action.setValue(true, forKey: "checked")
alert.addAction(action)
}
let cancel = UIAlertAction(title: L10n.cancel, style: .cancel, handler: nil)
alert.addAction(cancel)
DispatchQueue.main.async { // must be async !!
uiViewController.present(alert, animated: true, completion: {
self.show = false // hide holder after alert dismiss
})
}
}
}
}
并显示:
.background(WhatsappAlertController(show: self.$showWhatsAppActionSheet, viewModel: viewModel))