How to make Hosting View transparent in SwiftUI?

Viewed 740

I need nearly all of the views in my app to have a transparent background, including TabView and NavigationView which by default have opaque backgrounds. I’ve mostly been able to accomplish by setting the default background of UIView to .clear by adding the following code to my .onAppear() function.

UIView.appearance().backgroundColor = .clear

However, while this works for most of the views, I noticed that Hosting View still retains its opaque background. So I was wondering how I might be able to make the background of this view transparent?

Here is a view hierarchy capture of the problematic views when applying .clear to the UIView background. While I’ve actually managed to remove the background of these views using Introspect, this workaround doesn't seem to work correctly when running my app on an actual device (some views remain opaque, others for some reason only become transparent after switching the color scheme during runtime). So how else might I be able to accomplish this?

Any help or suggestions would be greatly appreciated!

1 Answers

This will add SwiftUI View with clear background as a child view controller:

struct SwiftUIView: View {
    var body: some View {
        VStack{
            HStack{
                Text("Testing Hosting VC")
            }
        }.font(.headline)
    }
}

struct SwiftUIView_Previews: PreviewProvider {
    static var previews: some View {
        SwiftUIView()
    }
}


class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = UIColor.blue
        
        let hostingController = UIHostingController(rootView: SwiftUIView())
        hostingController.view.isOpaque = false
        hostingController.view.backgroundColor = UIColor.clear
        addChild(hostingController)
        hostingController.view.translatesAutoresizingMaskIntoConstraints = false
        view.addSubview(hostingController.view)
        hostingController.view.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
        hostingController.view.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
        hostingController.didMove(toParent: self)
    }
}
Related