Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove background from NavigationStack in SwiftUI

In my app, I want to construct a single background view under my NavigationStack and then show that same background underneath other views that I navigate to via NavigationLinks. I am trying to do this by putting the NavigationStack and my background in a ZStack, but after inspecting the view hierarchy of the app I can see that the NavigationStack is showing its own background in the hosting view controller, and I can't for the life of me figure out how to make it transparent.

Here is a simplified version of my view:

struct Drawer: View {
    @State private var selection: DrawerMenuItem? = DrawerMenuItems().options.first

    var body: some View {
        ZStack {
            Color.blue.ignoresSafeArea()
            
            NavigationStack(path: $path) {
                List(DrawerMenuItems().options, selection: $selection) { item in
                    NavigationLink(destination: AnyView(item.view)) {
                        //Trimmed for brevity
                    }
                }
                .scrollContentBackground(.hidden)
            }
        }
    }
}

And here is a screenshot of the resulting view hierarchy:

View Hierarchy

I am currently using Xcode 15 beta with Swift 5, targeting iOS 17.

like image 612
Timestretch Avatar asked Mar 23 '26 17:03

Timestretch


1 Answers

There no direct way to remove NavigationStack background color.

There is an excellent library called SwiftUIIntrospect that provides additional functionality for SwiftUI views. Using that we can access underlying UIKit components of SwiftUI view and we can manipulate that.

with help of this library we can remove the background of NavigationStack

import SwiftUI
import SwiftUIIntrospect

struct Drawer: View {
    var body: some View {
        ZStack {
            Color.blue.ignoresSafeArea()
            NavigationStack {
                Text("Hello")
            }
            .introspect(.navigationStack, on: .iOS(.v16, .v17)) {
                $0.viewControllers.forEach { controller in
                    controller.view.backgroundColor = .clear
                }
            }
        }
    }
}
like image 148
Anbalagan D Avatar answered Mar 26 '26 09:03

Anbalagan D



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!