Add a List View in SwiftUI
Written by Team Kodeco
The List
view in SwiftUI is a powerful tool for displaying a list of items in a scrollable view. It’s commonly used to present data in an organized and easy-to-read manner. In this cookbook entry, you’ll learn how to add a List view to your SwiftUI app.
Imagine you want to build a simple to-do list app. Here’s an example of how you can use the List view to display a list of tasks:
struct ContentView: View {
let tasks = ["Task 1", "Task 2", "Task 3", "Task 4", "Task 5"]
var body: some View {
List(tasks, id: \.self) { task in
Text(task)
}
}
}
You should see the following in the preview:
In the code, we first create a struct called ContentView
that conforms to the View
protocol. Inside the struct, we define an array of tasks that we want to display in the List
view.
We then use the List
view with the tasks
array as its data source. The id
parameter represents a unique identifier for each item in the list, which is necessary for SwiftUI to efficiently update the view. We use \.self
to specify that we want to use the task string itself as the identifier.
Finally, we use a closure to specify how each task should be displayed in the List view. In this case, we simply display the task as a Text
view.
For more details, see the “Lists & Navigation in SwiftUI” section in this cookbook.