view - 在 SwiftUI 中呈现视图控制器
问题描述
如何使用 SwiftUI 实现以下 Objective-C 代码实现的目标?我一直无法牢牢掌握所提出的想法。
[self presentViewController:messageViewController animated:YES completion:nil];
解决方案
直到 ios 13.x,SwiftUI 都没有提供方法。由于我有同样的需求,写了一个自定义的 View 修饰符来实现它。
extension View {
func uiKitFullPresent<V: View>(isPresented: Binding<Bool>, style: UIModalPresentationStyle = .fullScreen, content: @escaping (_ dismissHandler: @escaping () -> Void) -> V) -> some View {
self.modifier(FullScreenPresent(isPresented: isPresented, style: style, contentView: content))
}
}
struct FullScreenPresent<V: View>: ViewModifier {
@Binding var isPresented: Bool
@State private var isAlreadyPresented: Bool = false
let style: UIModalPresentationStyle
let contentView: (_ dismissHandler: @escaping () -> Void) -> V
@ViewBuilder
func body(content: Content) -> some View {
if isPresented {
content
.onAppear {
if self.isAlreadyPresented == false {
let hostingVC = UIHostingController(rootView: self.contentView({
self.isPresented = false
self.isAlreadyPresented = false
UIViewController.topMost?.dismiss(animated: true, completion: nil)
}))
hostingVC.modalPresentationStyle = self.style
UIViewController.topMost?.present(hostingVC, animated: true) {
self.isAlreadyPresented = true
}
}
}
} else {
content
}
}
}
并且,您可以按以下方式使用它。
.uiKitFullPresent(isPresented: $isShowingPicker, content: { closeHandler in
SomeFullScreenView()
.onClose(closeHandler) // '.onClose' is a custom extension function written. you can invent your own way to call 'closeHandler'.
})
content
parameter of.uiKitFullPresent
是一个以回调处理程序作为参数的闭包。您可以使用此回调来关闭呈现的视图。
到目前为止,它运作良好。不过看起来有点棘手。
如您所知,iOS 14 将为我们带来一种以您想要的方式呈现任何视图的方法。退房fullScreenCover()
。
关于呈现由Objective-C编写的UIViewController,正如Asperi在他的帖子中提到的那样是可能的。
更新
这是我目前使用的完整源代码。
https://gist.github.com/fullc0de/3d68b6b871f20630b981c7b4d51c8373
推荐阅读
- python - 如何在箱线图中收集图和标签轴
- python - 在 Python 中过滤分组和聚合的数据
- opencart - 我也会遇到 opecart 3.0.3.3 的翻译问题
- node.js - 如何在功能前在 mocha 测试中启动 serverless-offline
- excel - 从 Excel 中删除链接文件
- r - 替换 R 中数据框中出现值的位置
- node.js - 模型表未在 mysql loopback 3 中自动创建
- python - 如何在 android (kivy) 上通过 python 多处理使用共享内存?
- vb.net - 在 VB.Net 2019 中一一播放不同的 MP3 文件
- neo4j - 在 Neo4j 中,如何在一个节点和一组其他节点之间创建关系?