List
Render collections with List using identifiable items.
Basic List
Render a list of items using List and ForEach.
Example
Demo.swift
ContentView.swift
App.swift
import SwiftUI
struct Item: Identifiable { let id: Int; let title: String }
struct ListBasicDemo: View {
let items = [Item(id: 1, title: "Milk"), Item(id: 2, title: "Bread")]
var body: some View { List(items) { Text($0.title) } }
}
The example above shows a list of items using List and ForEach.
Custom rows with ForEach
Render a list of items using List and ForEach.
Example
Demo.swift
ContentView.swift
App.swift
import SwiftUI
struct Product: Identifiable { let id: Int; let name: String; let price: Double }
struct ListCustomRowsDemo: View {
let items = [
Product(id: 1, name: "Coffee", price: 2.99),
Product(id: 2, name: "Tea", price: 1.99)
]
var body: some View {
List {
ForEach(items) { p in
HStack { Text(p.name); Spacer(); Text(String(format: "$%.2f", p.price)) }
}
}
}
}
Leave a Reply