iosswiftuiswiftui-list

Permanently Make List's Section Headers Transparent


I need transparent section headers in a SwiftUI List that stay transparent when they become sticky during scrolling.

Using SwiftUI Introspect, I can make headers transparent initially, but UIKit re-adds the background when they become sticky.

List {
    ForEach(grouppedMessages, id: \.date) { group in
        Section {
            ForEach(group.messages, id: \.id) { message in
                MessageView(message: message)
                    .listRowBackground(Color.clear)
            }
        } header: {
            HeaderView(date: group.date)
                .introspect(.listCell, on: .iOS(.v17)) { cell in
                    // Works initially, but background returns when sticky
                    let backgroundView = cell.subviews.first {
                                    $0.description.contains("_UICollectionViewListCellBackgroundView")
                    }
                    backgroundView?.backgroundColor = .clear
                    backgroundView?.alpha = 0
                    backgroundView?.isHidden = true
                }
        }
    }
}
.listStyle(.plain)
.scrollContentBackground(.hidden)

Screenshot: enter image description here

Tried:

How to keep section headers transparent when they become sticky? Alternative approaches welcome. Besides rewriting this to UIKit.


Solution

  • If you are fine with using SwiftUI-Introspect, you can set backgroundConfiguration.

    } header: {
        Text("Header")
            .introspect(.listCell, on: .iOS(.v17, .v18)) {
                $0.backgroundConfiguration = .clear()
            }
            
    }
    

    I have not been able to find a situation where the background color is reset without introspect being called.