listswiftuiheader

SwiftUI - Avoid translucent background for List header


I have a simple List with a header like this:

NavigationStack{
  List{
    Section{
      View()
    }header:{
       Text("Section Header")
     }
  }
  .listStyle(.plain)
}

and when scrolling the list, the header gets this weird translucent background that I hate:

enter image description here

Is there a way to make the background not translucent, just dark or light based on the color scheme? I tried to set the section background to clear or custom colors with no success.


Solution

  • If I understand correctly, you want to set the background for the section header, right?

    You can do this by applying a .background to the text of the header.

    Text("Section Header")
        .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .leading)
        .listRowInsets(.init(top: 0, leading: 0, bottom: 0, trailing: 0))
        .padding(.leading, 20)
        .background(.background)
    

    Screenshot

    This screenshot is from an iPhone 15 running iOS 17.4. The only other difference to the code in your post is that .background(.yellow) is being applied after the .listStyle modifier. Otherwise, the rest of the code is the same.