Introduction
A list view shows many items in a scrollable column. It helps users see and pick from multiple things easily.
A list view shows many items in a scrollable column. It helps users see and pick from multiple things easily.
import SwiftUI struct ContentView: View { let items = ["Apple", "Banana", "Cherry"] var body: some View { List(items, id: \.self) { item in Text(item) } } }
The List view creates a scrollable list of rows.
Use id: \.self when your data items are simple and identifiable by themselves.
List(["Red", "Green", "Blue"], id: \.self) { color in Text(color) }
List {
Text("First item")
Text("Second item")
Text("Third item")
}Identifiable protocol.struct Fruit: Identifiable {
let id = UUID()
let name: String
}
let fruits = [Fruit(name: "Mango"), Fruit(name: "Peach")]
List(fruits) { fruit in
Text(fruit.name)
}This app shows a scrollable list of fruit names with a title on top.
import SwiftUI struct ContentView: View { let fruits = ["Apple", "Banana", "Cherry", "Date"] var body: some View { NavigationView { List(fruits, id: \.self) { fruit in Text(fruit) } .navigationTitle("Fruit List") } } } @main struct MyApp: App { var body: some Scene { WindowGroup { ContentView() } } }
List automatically scrolls if items don't fit on screen.
Use id: \.self only for simple, unique data like strings.
For complex data, use Identifiable protocol to help SwiftUI track items.
List shows many items vertically and scrolls if needed.
Use List(data, id: \.self) for simple lists.
Use Identifiable for custom data types in lists.
List view in SwiftUI primarily do?fruits?struct ContentView: View {
let numbers = [1, 2, 3]
var body: some View {
List(numbers, id: \.self) { num in
Text("Number: \(num * 2)")
}
}
}struct ContentView: View {
let items = ["A", "B", "C"]
var body: some View {
List(items) { item in
Text(item)
}
}
}Person conforming to Identifiable with a unique id. How do you create a List to display each person's name?Pass the test and this pattern moves unknown