5 view presentviewcontroller swiftui
如何使用 SwiftUI 实现以下 Objective-C 代码实现的功能?我一直无法牢牢掌握所提出的想法。
[self presentViewController:messageViewController animated:YES completion:nil];
Run Code Online (Sandbox Code Playgroud)
Kyo*_*ang 10
直到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
}
}
}
Run Code Online (Sandbox Code Playgroud)
并且,您可以按如下方式使用它。
.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'.
})
Run Code Online (Sandbox Code Playgroud)
content
parameter of.uiKitFullPresent
是一个以回调处理程序作为参数的闭包。您可以使用此回调来关闭所呈现的视图。
到目前为止效果很好。不过看起来有点棘手。
如您所知,iOS 14将为我们带来一种以您想要的方式呈现任何视图的方法。查看fullScreenCover()
。
关于呈现 Objective-C 编写的 UIViewController,正如 Asperi 在他的文章中提到的那样,这是可能的。
更新
这是我迄今为止使用的完整源代码。
https://gist.github.com/fullc0de/3d68b6b871f20630b981c7b4d51c8373
UPDATE_2
现在,我想说这不是一个好方法,因为底层的想法实际上似乎与 SwiftUI 的机制不太匹配。
由于没有提供相关代码,所以在伪代码中它看起来像下面这样
struct YourParentView: View {
@State private var presented = false
var body: some View {
// some other code that activates `presented` state
SomeUIElement()
.sheet(isPresented: $presented) {
YourMessageViewControllerRepresentable()
}
}
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
5911 次 |
最近记录: |