简体   繁体   中英

How to present crossDissolve view in swiftUI?

In UIKit I used below code to present a modal Viewcontroller with presentation style crossDissolve

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

But how I can achieve this in swiftUI?

You can make an extension on UIViewController like this:


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:


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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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