如何忽略SwiftUI模态背景​​,或使模态背景清晰/透明? [英] How to ignore SwiftUI modal background, or make modal background clear/transparent?

查看:114
本文介绍了如何忽略SwiftUI模态背景​​,或使模态背景清晰/透明?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前,我们为swiftUI模态提供了免费的不透明白色/黑色背景.无论如何,有没有消除自由的不透明颜色并使模态视图透明的方法?

Currently we get a free opaque white/black background for swiftUI modal. Is there anyway to remove the free opaque color and make the modal view transparent?

在下面的图像中,即使在呈现模态的情况下,最终结果也应该能够看到该图像.

In the image below, the end result should be able to see the image even with modal presented.

推荐答案

基于此代码段您可以创建viewcontroller扩展名并修改您的演示文稿. 这是修改后的代码:

based on this code snippet you can create viewcontroller extension and modify your presentation. here is modified code:

 struct ViewControllerHolder {
    weak var value: UIViewController?
    init(_ value: UIViewController?) {
        self.value = value
    }
}

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

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

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

        toPresent.view.backgroundColor = .clear // This line is modified
        self.present(toPresent, animated: animated, completion: completion)
    }
}

您的SwiftUI ContentView:

Your SwiftUI ContentView:

struct ContentView: View {

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

    var body: some View {
        ZStack {
            Color.red
            Button(action: {
                self.viewController?.present(builder: {
                    Text("OK")
                })
            }) {
               Text("Present me!")
            }
        }
    }
}

这篇关于如何忽略SwiftUI模态背景​​,或使模态背景清晰/透明?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆