How to Use List in SwiftUI: Syntax and Examples
In SwiftUI, use the
List view to display a scrollable list of rows. You provide a collection and a closure that defines how each item appears. List automatically handles scrolling and layout for you.Syntax
The basic syntax of List involves passing a collection and a closure that creates a view for each item. You can also create static lists by directly adding views inside List.
- Collection-based List:
List(data) { item in ... } - Static List:
List { Text("Row 1") Text("Row 2") }
swift
List(items) { item in
Text(item.name)
}Example
This example shows a list of fruit names displayed in a scrollable list. Each row shows the fruit's name.
swift
import SwiftUI struct Fruit: Identifiable { let id = UUID() let name: String } struct ContentView: View { let fruits = [Fruit(name: "Apple"), Fruit(name: "Banana"), Fruit(name: "Cherry")] var body: some View { List(fruits) { fruit in Text(fruit.name) } } }
Output
A scrollable list showing rows: Apple, Banana, Cherry
Common Pitfalls
Common mistakes include:
- Not making your data identifiable by conforming to
Identifiableor providing anidparameter. - Using mutable data without proper state management, causing UI not to update.
- Forgetting to use unique IDs, which can cause rendering issues.
swift
/* Wrong: Data without Identifiable or id */ struct Item { let name: String } List(items) { item in Text(item.name) } /* Right: Make Item Identifiable */ struct Item: Identifiable { let id = UUID() let name: String } List(items) { item in Text(item.name) }
Quick Reference
- List(data) { item in ... }: Create a list from a collection.
- List { ... }: Create a static list with fixed views.
- Identifiable: Your data must conform to this or use
id:parameter. - ForEach: Use inside List for complex layouts.
Key Takeaways
Use
List to create scrollable lists easily in SwiftUI.Your data must conform to
Identifiable or provide a unique id.You can create dynamic lists from collections or static lists with fixed views.
Use
ForEach inside List for more complex row layouts.Avoid mutable data without state management to ensure UI updates correctly.