0

Consider a NavigationView containing a List of items. How does one give this a background color?

  • Putting the NavigationView in a ZStack - doesn't work
  • Putting the ZStack in the NavigationView (code sample below) - doesn't work
struct test: View {
    var body: some View {
        NavigationView {
            ZStack {
                Color.blue
                List {
                    ForEach(["1", "2", "3"], id: \.self) { item in
                        NavigationLink(destination: EmptyView()) {
                            Text("Some title")
                        }
                    }
                }
                .navigationTitle("Items")
            }
        }
    }
}

background color of list in navigationview - not working

Arjan
  • 16,210
  • 5
  • 30
  • 40

2 Answers2

0
  • Combine putting the ZStack inside the NavigationView with setting the appearance of UITableView onAppear of the List.
  • Set .listRowBackground on the ForEach to have the cells get the same background color.
struct test: View {
    var body: some View {
        NavigationView {
            ZStack {
                Color.blue.edgesIgnoringSafeArea(.all)
                List {
                    ForEach(["1", "2", "3"], id: \.self) { item in
                        NavigationLink(destination: EmptyView()) {
                            Text("Some title")
                        }
                    }.listRowBackground(Color.blue)
                }
                .onAppear() {
                    UITableView.appearance().backgroundColor = UIColor.clear
                    UITableViewCell.appearance().backgroundColor = UIColor.clear
                }
                .navigationTitle("Items")
            }
        }
    }
}

background color of list in navigationview - working

Arjan
  • 16,210
  • 5
  • 30
  • 40
0

If you don't want to change the appearance of every List and Form in your app, you can use SwiftUI-Introspect.

I changed the list row background color in SwiftUI, and set the background with Introspect so it only affects this List and no other.

Code:

NavigationView {
    List {
        ForEach(["1", "2", "3"], id: \.self) { item in
            NavigationLink(destination: EmptyView()) {
                Text("Some title")
            }
            .listRowBackground(Color.blue)
        }
    }
    .introspectTableView { tableView in
        tableView.backgroundColor = .systemBlue
    }
    .navigationTitle("Items")
}

Note: UIKit's .systemBlue is equivalent to SwiftUI's .blue.

George
  • 25,988
  • 10
  • 79
  • 133