Set SwiftUI List View transparent background 1

Set SwiftUI List View transparent background

When we use List View in SwiftUI, we will find that even if we set the background image to the Navigation view underneath, the background of List View is still white by default. Using .background(Color.clear) to modify the List has no effect. Many solutions on the web suggest using other methods, such as using VStack instead of List, but this method is sometimes inconvenient, e.g., I sometimes want to use .onDelete on the List view, but if I use VStack instead, it will be very troublesome.

After a period of time fiddling I finally determined how to set SwiftUI List View transparent background complete solution, because the Internet seems to be very difficult to find this solution, so here to explain.

First of all, we know that List view is actually the former UITableView, in order to set the background color, we can add an initialize(): in our view.

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

Again, 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 will see that the background of the list has finally become transparent. However, the list item inside will still have a white background. This is because the list row has its own settings, so we have to set the transparent background for the list row separately.

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

After setting the listRowBackground, we can finally see the ListView appearing on NavigationView with full transparent background.


Thank you for reading this post. If you like my post, please follow up withFacebook Fan Specialist,Twitter,IGThe

Leave a ReplyCancel reply