swift - SwiftUI:UIAlertController ActionSheet 全屏
问题描述
我正在尝试在 SwiftUI 中实现一个选中标记的操作表View
。我正在使用 a
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 来实现复选标记?
解决方案
我的错误是没有创建一个持有者控制器,一个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))
推荐阅读
- ios - IAB.close() 调用但它已经关闭
- python - 尝试导入包时出现python ModuleNotFoundError
- python - Python分而治之的递归搜索
- r - 将 OS National Grid 名称/代码添加到 R 中的网格
- sql - 此表的主键类型是什么?
- python - 单元格合并很慢 python-docx
- html - 如何通过单击按钮来扩展 mat-table 中的扩展面板?
- javascript - 剑道数字文本框删除尾随零
- angular - 带有键值管道的角度材料自动完成过滤器对象
- javascript - 反应上下文 api 以替换 redux 存储