how to write a list in swiftui

Asked on 07/30/2024

1 search

To write a list in SwiftUI, you can use the List view, which is a powerful and flexible way to display a collection of data. Here are some key points and examples from the WWDC sessions:

  1. Basic List Initialization:

    • You can initialize a List with a collection of data. This is a convenient way to create a ForEach view, which generates views for each element in the collection and provides them to its container.
    • Example:
      struct Pet: Identifiable {
          let id = UUID()
          let name: String
      }
      
      let pets = [Pet(name: "Whiskers"), Pet(name: "Rufus"), Pet(name: "Bubbles")]
      
      struct PetListView: View {
          var body: some View {
              List(pets) { pet in
                  Text(pet.name)
              }
          }
      }
      
  2. Customizing Lists:

    • Lists can be customized through the use of view modifiers. For example, you can add swipe actions to each row.
    • Example:
      struct PetListView: View {
          var body: some View {
              List(pets) { pet in
                  Text(pet.name)
                      .swipeActions {
                          Button("Delete") {
                              // Handle delete action
                          }
                          .tint(.red)
                      }
              }
          }
      }
      
  3. Using ForEach within a List:

    • You can also create a list by manually writing out a set of views or by using a ForEach view.
    • Example:
      struct PetListView: View {
          var body: some View {
              List {
                  ForEach(pets) { pet in
                      Text(pet.name)
                  }
              }
          }
      }
      
  4. Searchable Lists:

    • You can make a list searchable by adding the searchable modifier.
    • Example:
      struct PetListView: View {
          @State private var searchTerm = ""
      
          var body: some View {
              List {
                  ForEach(pets.filter { searchTerm.isEmpty || $0.name.contains(searchTerm) }) { pet in
                      Text(pet.name)
                  }
              }
              .searchable(text: $searchTerm)
          }
      }
      

For more detailed information, you can refer to the following sessions from WWDC:

These sessions cover the basics of creating and customizing lists in SwiftUI, as well as more advanced topics like composition and state management.