如何在 swiftUI 中呈现 crossDissolve 视图?

How to present crossDissolve view in swiftUI?

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

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

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

您可以像这样对 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!")
        }
    }
}

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