ForEach trong SwiftUI
1. Với Identifiable
struct Item: Identifiable {
let id = UUID()
let name: String
}
ForEach(items) { item in
Text(item.name)
}2. Với id Parameter
ForEach(["A", "B", "C"], id: \.self) { letter in
Text(letter)
}
ForEach(0..<5) { index in
Text("Item \(index)")
}3. Binding in ForEach
struct TodoList: View {
@State var todos: [Todo]
var body: some View {
List {
ForEach($todos) { $todo in
Toggle(todo.title, isOn: $todo.isComplete)
}
}
}
}4. Indexed ForEach
ForEach(Array(items.enumerated()), id: \.offset) { index, item in
Text("\(index + 1). \(item.name)")
}5. Trong Stacks
VStack {
ForEach(items) { item in
ItemRow(item: item)
}
}
HStack {
ForEach(colors, id: \.self) { color in
Circle().fill(color).frame(width: 30)
}
}6. Grid với ForEach
let columns = [GridItem(.adaptive(minimum: 100))]
LazyVGrid(columns: columns) {
ForEach(photos) { photo in
Image(photo.name)
.resizable()
.aspectRatio(1, contentMode: .fill)
}
}📝 Tóm tắt
// Identifiable
ForEach(items) { item in }
// Custom id
ForEach(items, id: \.someProperty) { item in }
// Range
ForEach(0..<10) { i in }
// Binding
ForEach($items) { $item in }Last updated on