如何在swiftUI中呈现crossDissolve视图?

时间:2020-02-25 09:26:50

标签: ios swiftui ios13

在UIKit中,我使用下面的代码来呈现具有呈现方式 crossDissolve

的模式Viewcontroller。
controller.modalTransitionStyle = .crossDissolve
controller.modalPresentationStyle = .overFullScreen
UIApplication.topViewController()?.present(controller, animated: true, completion: nil)

但是我如何在swiftUI中实现这一目标?

1 个答案:

答案 0 :(得分:2)

您可以像这样在UIViewController上进行扩展:


struct ViewControllerHolder {
    weak var value: UIViewController?
}

struct ViewControllerKey: EnvironmentKey {
    static var defaultValue: ViewControllerHolder {
        return ViewControllerHolder(value: UIApplication.shared.windows.first?.rootViewController)

    }
}

extension EnvironmentValues {
    var viewController: UIViewController? {
        get { return self[ViewControllerKey.self].value }
        set { self[ViewControllerKey.self].value = newValue }
    }
}

extension UIViewController {
    func present<Content: View>(style: UIModalPresentationStyle = .automatic, transitionStyle: UIModalTransitionStyle = .coverVertical, @ViewBuilder builder: () -> Content) {
        let toPresent = UIHostingController(rootView: AnyView(EmptyView()))
        toPresent.modalPresentationStyle = style
        toPresent.modalTransitionStyle = transitionStyle
        toPresent.rootView = AnyView(
            builder()
                .environment(\.viewController, toPresent)
        )
        self.present(toPresent, animated: true, completion: nil)
    }
}

并根据需要在SwiftUI代码中使用它:


struct ContentView: View {

    @Environment(\.viewController) private var viewControllerHolder: UIViewController?
    private var viewController: UIViewController? {
        self.viewControllerHolder
    }

    var body: some View {
        Button(action: {
            self.viewController?.present(style: .fullScreen, transitionStyle: .coverVertical) {
              Text("OK")
           }
        }) {
           Text("Present me!")
        }
    }
}

通过这种方式,您可以根据需要更改演示文稿和过渡样式