In previous post, we learned how to create a List with custom rows. Today, we are going to extend our List by adding a section with a header and a footer. On top of that, we’re going to use a technique which hides empty rows in the List to make it look like this:

This look can be achieved by using a ForEach structure which makes a view from an underlying data.
struct ContentView: View {
let hikingTrails = [
Trail(name: "Stanford Dish", location: "Palo Alto", distance: 3.9),
Trail(name: "Edgewood", location: "Redwood City", distance: 3.2),
Trail(name: "Mission Peak", location: "Fremont", distance: 7.1),
Trail(name: "Big Basin", location: "Boulder Creek", distance: 4.3),
Trail(name: "Alum Rock", location: "Milpitas", distance: 5.7),
]
var body: some View {
List {
Section(header: ListHeader(), footer: ListFooter()) {
ForEach(hikingTrails) { trail in
TrailRow(trail: trail)
}
}
}.listStyle(GroupedListStyle())
}
}
struct ListHeader: View {
var body: some View {
HStack {
Image(systemName: "map")
Text("Hiking Trails in Silicon Valley")
}
}
}
struct ListFooter: View {
var body: some View {
Text("Remember to pack plenty of water and bring sunscreen.")
}
}
Creating List sections can be achieved by using a Section structure which also allows us to specify custom header and footer views.
Finally, use the listStyle modifier to pick default system appearance for the List sections:
listStyle(GroupedListStyle())
Related tutorials:
- How to add NavigationView to List in SwiftUI and show detail view using NavigationLink
- How to add button to navigation bar in SwiftUI
- How to present new sheet view from navigationBarItems button in SwiftUI
Questions, comments or suggestions? Follow us on Twitter @theswiftguide