如何在swiftUI中呈现crossDissolve视图?

Samiul Islam Sami |

在UIKit中,我使用下面的代码以演示样式crossDissolve呈现了模态Viewcontroller

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

但是如何在swiftUI中实现呢?

Mac3n

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

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章