Reading time: 1 min

This recipe shows how to add a sticky header to a List in SwiftUI. It also allows for a scrolling part of the header, as well as multiple sticky headers.

The end result looks like this:

preview

The recipe goes as follows:

  • Use Section(header:) to define the sticky header and the content beneath it.
  • Set listStyle to .plain / PlainListStyle().

Here's the full code:

List {
  Text("Non-sticky part of the header...")
    .font(.system(size: 32))

  Section(header: HStack {
    Text("Sticky header")
      .font(.system(size: 24))
    Spacer()
    Image(systemName: "sun.max.fill")
  }) {
    ForEach(1..<40) { index in
      Text("Row #\(index)")
    }
  }
}
.listStyle(.plain) // PlainListStyle() on SwiftUI 1 and 2

The same formula works for multiple sticky headers as well:

preview_multiple

List {
  Text("Non-sticky part of the header...")
    .font(.system(size: 32))

  Section(header: HStack {
    Text("Sticky header")
      .font(.system(size: 24))
    Spacer()
    Image(systemName: "sun.max.fill")
  }) {
    ForEach(1..<40) { index in
      Text("Row #\(index)")
    }
  }

  Section(header: HStack {
    Text("Sticky header 2")
      .font(.system(size: 24))
    Spacer()
    Image(systemName: "sun.max.fill")
  }) {
    ForEach(1..<40) { index in
      Text("Row #\(index)")
    }
  }
}
.listStyle(.plain) // PlainListStyle() on SwiftUI 1 and 2

Next Post Previous Post