How to ignore SwiftUI modal background, or make modal background clear/transparent?

寵の児 提交于 2020-03-17 03:16:31

问题


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.


回答1:


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)
    }
}

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!")
            }
        }
    }
}


来源:https://stackoverflow.com/questions/60264777/how-to-ignore-swiftui-modal-background-or-make-modal-background-clear-transpare

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!