Setting transparent background for List view in SwiftUI

Today I encountered the issue that when I set up a List view, the List background is always white, even though I actually have a background image on the underlying NavigationView. I tried to configure the List with .background(Color.clear) but there was no effect. Searching for answers lots of articles suggesting workarounds like replacing List by a VStack. That didn’t really work for me because I need the convenience such as .onDelete etc from List view.

At the end here is what actually works. (I am a little surprised I couldn’t find a complete solution somewhere. Maybe I was bad at Googling)

First, the List view itself is essentially a UITableView. To set the background color properly, I added an initialize() function for my view:

func initialize(){
        UITableView.appearance().backgroundColor = .clear
        UITableViewCell.appearance().backgroundColor = .clear
        UITableView.appearance().tableFooterView = UIView()
 }

Then, we call this initialize() when the List is loaded.

List {
   //Your list contents here, e.g.
   ForEach(data) { index in 
       MyRowView(data: data[index]) 
   }
}
.onAppear{
      self.initialize()
}

After this step, we can see the List background became transparent. However, the List items are still with white background. It turns out the List rows have their own configuration. So we have to give the rows the clear background too.

struct MyRowView: View {
    ...
    var body: Some View {
         VStack{ //This can be any view actually
             //More contents...
         }.listRowBackground(Color.clear)
    }
} 

Finally I am seeing the entire list showing up with the proper background image I configured for my NavigationView underneath.

Leave a ReplyCancel reply