Learn how to create lists and scrollable content.
The List
view displays a collection of rows, which can be static or dynamic.
List {
Text("Item 1")
Text("Item 2")
Text("Item 3")
}
Explanation:
List
: Creates a list view.Text("Item 1")
: Displays a text view with the string "Item 1".Text("Item 2")
: Displays a text view with the string "Item 2".Text("Item 3")
: Displays a text view with the string "Item 3".Dynamic lists use an array of data to populate their rows.
let items = ["Item 1", "Item 2", "Item 3"]
var body: some View {
List(items, id: \.self) { item in
Text(item)
}
}
Explanation:
let items = ["Item 1", "Item 2", "Item 3"]
: Declares an array of strings.List(items, id: \.self) { item in Text(item) }
: Creates a list view with dynamic rows. Each row displays a text view with the corresponding item.Using a model to create custom list items.
struct Item: Identifiable {
let id = UUID()
let name: String
}
let items = [
Item(name: "Item 1"),
Item(name: "Item 2"),
Item(name: "Item 3")
]
var body: some View {
List(items) { item in
Text(item.name)
}
}
Explanation:
struct Item: Identifiable
: Defines a model that conforms to the Identifiable
protocol. This is necessary for SwiftUI to uniquely identify each item in the list.let id = UUID()
: Generates a unique identifier for each item.let name: String
: Stores the name of the item.let items = [Item(name: "Item 1"), Item(name: "Item 2"), Item(name: "Item 3")]
: Creates an array of items.List(items) { item in Text(item.name) }
: Creates a list view with dynamic rows. Each row displays a text view with the item's name.The ScrollView
allows for scrolling content within a view.
ScrollView {
VStack {
ForEach(0..<50) { index in
Text("Item \(index)")
.padding()
}
}
}
Explanation:
ScrollView
: Creates a scrollable view.VStack
: A vertical stack that arranges its children vertically.ForEach(0..<50) { index in Text("Item \(index)").padding() }
: Iterates over the range 0 to 49, creating a text view for each index and adding padding around it.Using LazyVStack
and LazyHStack
for efficient rendering of large lists.
ScrollView {
LazyVStack {
ForEach(0..<100) { index in
Text("Lazy Item \(index)")
.padding()
}
}
}
Explanation:
LazyVStack
: A vertical stack that arranges its children lazily, only rendering the views that are currently visible. This improves performance for large lists.ForEach(0..<100) { index in Text("Lazy Item \(index)").padding() }
: Iterates over the range 0 to 99, creating a text view for each index and adding padding around it.