How to display list in SwiftUI

Generated on 9/6/2024

1 search

To display a list in SwiftUI, you can use the List view, which is a powerful tool for view composition. The List initializer can take a collection parameter, which is a convenience for creating a ForEach view. The ForEach view generates views for each element in a collection and provides those to its container. This allows you to create advanced constructions, such as multiple collections of data organized into sections.

Here's a basic example of how you might use a List in SwiftUI:

struct ContentView: View {
    let pets = ["Whiskers", "Rufus", "Bubbles"]

    var body: some View {
        List(pets, id: \.self) { pet in
            Text(pet)
        }
    }
}

In this example, the List is initialized with a collection of pet names. The ForEach view is used implicitly to generate a Text view for each pet name in the list.

Additionally, you can customize lists using view modifiers, such as adding swipe actions to each row. SwiftUI's declarative system ensures that when your view state changes over time, the UI is automatically kept up to date.

For more detailed information, you can refer to the session SwiftUI essentials (07:55) which covers the fundamentals of using lists in SwiftUI.