'SwiftUI: Background color of List with SidebarListStyle?

I have a SwiftUI List that has its listStyle set to SidebarListStyle. This gives me a List that looks like this:

enter image description here

Great! However, I would like to set a different background color on it, and can't seem to figure out how to do it. My code looks like this:

List {
   <snip>
}
.listStyle(SidebarListStyle())
.background(Color.yellow.ignoresSafeArea())

But, this effectively does nothing. My List looks exactly the same. How can I go about setting the background color for this List?



Solution 1:[1]

You can use this modifier .listRowBackground() for background color of a separate row.


struct ContentView: View {
    
    private var items = ["1", "2", "3"]
    
    init(){
        UITableView.appearance().backgroundColor = .purple // background color of list
    }
    
    var body: some View {
        List {
            ForEach(items, id: \.self) { item in
                Text(item)
                    .listRowBackground(Color.yellow) // background color of listRow
                Text(item)
                    .listRowBackground(Color.blue) // background color of listRow
            }
        }
        .frame(width: 300, height: 600)
    }
}



enter image description here

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1