List

#list

Overview

Subjects

Form vs List

  • Form is for User Input

  • List is for Presentation of data

Edge to Edge Color

Edge to edge color
.listStyle(.plain)

List with row number

Let list =["Car", "Bike", "Plane", "Boat"]
for(index, element) inlist.enumerated() {    
print(index, ":", element)}

// print: 0 : Car1 : Bike2 : Plane3 : Boat

List with Sections

VStack {
    List {
        ForEach(countries, id: \.self) { country in
            Section(country.wrappedFullName) {
                ForEach(country.candyArray, id: \.self) { candy in
                    Text(candy.wrappedName)
                }
            }
        }
    }

Sorted List

// FIRST METHOD
struct User: Identifiable {
    let id = UUID()
    let firstName: String
    let lastName: String
}

struct ContentView: View {
let users = [
    User(firstName: "Arnold", lastName: "Rimmer"),
    User(firstName: "Kristine", lastName: "Kochanski"),
    User(firstName: "David", lastName: "Lister"),
].sorted {
    $0.lastName < $1.lastName
}

//.............................

// SECOND METHOD

struct User: Identifiable {
    let id = UUID()
    let firstName: String
    let lastName: String
    
    static func <(lhs: User, rhs: User) -> Bool {
        lhs.lastName < rhs.lastName
    }
    
}

struct ContentView: View {
let users = [
    User(firstName: "Arnold", lastName: "Rimmer"),
    User(firstName: "Kristine", lastName: "Kochanski"),
    User(firstName: "David", lastName: "Lister"),
].sorted()
}

The result is the same on both methods. The benefit is, in case of using this list everywhere with same sorting method, we can change the sorting method in the struct and it changes everywhere we use the list.

Swipe Actions

Double Sided Swipe Action
List {
    Text("Taylor Swift")
        .swipeActions {
            Button(role: .destructive) {
                print("Hi")
            } label: {
                Label("Delete", systemImage: "minus.circle")
            }
        }
        .swipeActions(edge: .leading) {
            Button {
                print("Hi")
            } label: {
                Label("Pin", systemImage: "pin")
            }
            .tint(.orange)
        }
}
Hacking with Swift / 100 Days / Day-81 - Adding custom row swipe actions to a List

Other sources

Adding options with Swipe Actions

Sorting the List

Define the alternatives

enum SortOption {
    case alt1, alt1Reversed, alt2, alt2Reversed
    }

Convert enum type to variable and Publish it

@Published var sortOption: SortOption = .alt2

Sources

Videos

Articles / Documents

Last updated