简体   繁体   English

如何在 swiftUI 中呈现 crossDissolve 视图?

[英]How to present crossDissolve view in swiftUI?

In UIKit I used below code to present a modal Viewcontroller with presentation style crossDissolve在 UIKit 中,我使用下面的代码来呈现一个具有呈现样式crossDissolve的模态Viewcontroller

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

But how I can achieve this in swiftUI?但是我如何在 swiftUI 中实现这一点?

You can make an extension on UIViewController like this:你可以像这样在 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)
    }
}

and use it as you want in your SwiftUI code:并在您的 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!")
        }
    }
}

In this way, you have an ability to change your presentation and transition style as you want通过这种方式,您可以根据需要更改演示文稿和过渡样式

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM