在SwiftUI中呈现视图控制器

时间:2020-06-25 08:15:50

标签: view swiftui presentviewcontroller

如何通过SwiftUI实现以下Objective-C代码?我无法完全掌握所提出的想法。

    [self presentViewController:messageViewController animated:YES completion:nil];

2 个答案:

答案 0 :(得分:1)

由于没有提供相关代码,因此在伪代码中,它看起来像下面的

struct YourParentView: View {
   @State private var presented = false
   var body: some View {

      // some other code that activates `presented` state

      SomeUIElement()
         .sheet(isPresented: $presented) {
             YourMessageViewControllerRepresentable()
         }
   }
}

答案 1 :(得分:0)

直到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

.uiKitFullPresent参数是一个以回调处理程序作为其参数的闭包。您可以使用此回调来关闭显示的视图。

到目前为止效果很好。看起来有点棘手。

您可能知道,iOS 14将为我们带来一种以所需方式呈现任何视图的方法。检出fullScreenCover()

关于呈现由Objective-C编写的UIViewController,就像Asperi在他的帖子中提到的那样。