Search code examples
swiftlistuitableviewheaderswiftui

How to create header for List in SwiftUI?


I want to implement a header to a List in SwiftUI. I can do this using ScrollView but I want the properties of List (like lazy loading). There is a SectionHeader but that stays fixed on the top until the user scrolls to the end of that section and I don't want this behavior. I just want to scroll the whole view.

Is there a way of achieving this using SwiftUI?


Solution

  • It seems like you really just want a custom cell at the top of the List.

    Just use Sections. If you make it a plain section, with one entry, it will appear at the top, and scroll away when the view scrolls.

        List {
            Section() {
                YourCustomRowThatLooksLikeAHeader()
            }
    
            Section() {
                // Normal list stuff
                ForEach(offers, id: \.self) { offer in
                NavigationLink(
                    destination: DetailView(offer: offer)
                ) {
                    HStack {
                        Image(offer.offerThumbnail ?? "")
                        Text("\(offer.shortInfo ?? "")")
                    }
                }
                    
            }
        }