swiftuibackgroundswiftui-navigationview

How to add background color to a view with a NavigationStack?


I'm trying to put a background color in this View, but apparently having NavigationStack prevents it from appearing. Is there any other way I can implement this?

import SwiftUI

struct DiscoverView: View {
    private let adaptiveColumns = [
        GridItem(.adaptive(minimum: 120))
    ]
    
    var body: some View {
        ZStack {
            Color.primaryApp.ignoresSafeArea(.all)

            NavigationStack {
                ScrollView {
                    LazyVGrid(columns: adaptiveColumns, spacing: 60) {
                        ForEach(playlists) { playlist in
                            NavigationLink(destination: ContentView()) {
                                PlaylistCardView(playlist: playlist)
                            }
                            .foregroundStyle(.primary)
                        }
                    }
                    .padding()
                }
            }
        }
    }
}

This is the code I'm using in DiscoverView, if necessary I'll make other parts of the code available.


Solution

  • You can just apply a background behind the ScrollView. So you probably don't need the ZStack:

    var body: some View {
        NavigationStack {
            ScrollView {
                // content as before
            }
            .background(Color.primaryApp)
        }
    }
    

    Note that the safe areas are ignored by default when using this modifier. See background(_:ignoresSafeAreaEdges:).