article

Tuesday, November 9, 2021

SwiftUI Customize List with section header and footer

SwiftUI Customize List with section header and footer

ContentView.swift
 
//
//  ContentView.swift
//  Swiftuitest
//
//  Created by Cairocoders
//

import SwiftUI

struct ContentView: View {

    let hikingTrails = [
        Trail(name: "Mount Pinatubo", location: "Botolan", distance: 2.9),
        Trail(name: "Mount Balingkilat", location: "Subic", distance: 1.2),
        Trail(name: "Sampaloc Cove", location: "Subic", distance: 1.1),
        Trail(name: "Mount Tapulao", location: "Palauig", distance: 1.3),
        Trail(name: "Pundakit", location: "San Antonio", distance: 2.7),
    ]
    
    var body: some View {
        VStack{
            GeometryReader { geometry in
                Image("details")
                    .resizable()
                    .aspectRatio(contentMode: .fill)
                    .frame(width: geometry.size.width, height: geometry.size.height)
                    .offset(y: geometry.frame(in: .global).minY/100)
                    .edgesIgnoringSafeArea(.all)
            }
            VStack {
                List {
                    Section(header: ListHeader(), footer: ListFooter()) {
                        ForEach(hikingTrails) { trail in
                            TrailRow(trail: trail)
                        }
                    }
                }.listStyle(GroupedListStyle())
            }
            Spacer()
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

struct ListHeader: View {
    var body: some View {
        HStack {
            Image(systemName: "map")
            Text("Best Trails in Zambales")
        }
    }
}

struct ListFooter: View {
    var body: some View {
        Text("Ready to check out the best trails in Zambales for hiking, mountain biking, climbing or other outdoor activities? AllTrails has 12 hiking trails, mountain biking routes, backpacking trips and more.")
    }
}

struct TrailRow: View {
    var trail: Trail
    
    var body: some View {
        HStack {
            VStack(alignment: .leading) {
                Text(trail.name)
                Text(trail.location).font(.subheadline).foregroundColor(.gray)
            }
            Spacer()
            Text(String(format: "%.1f miles", trail.distance))
        }
    }
}

struct Trail: Identifiable {
    var id = UUID()
    var name: String
    var location: String
    var distance: Double
}

Related Post