I wonder what is the right way to combine List and Grid with GridRows together?
In Apple's official tutorial on Model data with custom types there is the following example of Grid:
struct ContentView: View {
@State private var players: [Player] = [
Player(name: "Elisha", score: 0),
Player(name: "Andre", score: 0),
Player(name: "Jasmine", score: 0),
]
var body: some View {
VStack(alignment: .leading) {
Text("Score Keeper")
.font(.title)
.bold()
.padding(.bottom)
Grid {
GridRow {
Text("Player")
.gridColumnAlignment(.leading)
Text("Score")
}
.font(.headline)
ForEach($players) { $player in
GridRow {
TextField("Name", text: $player.name)
Text("\(player.score)")
Stepper("\(player.score)", value: $player.score)
.labelsHidden()
}
}
}
.padding(.vertical)
Button("Add Player", systemImage: "plus") {
players.append(Player(name: "", score: 0))
}
Spacer()
}
.padding()
}
}
And there is a practicing exercise which asks
Use a
Listview and anEditButtonso people can reorder the list of players.
No matter how I tried to integrate the List with EditButton in this view with Grid, I always failed.
If I embed the Grid inside of the List I get the only one item in the list which is not editable
If I use List inside of the Grid, the whole idea behind the usage of Grid doesn't make sense anymore since the alignment of the GridRows follows the List.
And in general, it feels like combining Grid and List is not a good idea and they should be used separately.
What do you think?
And in general, it feels like combining Grid and List is not a good idea and they should be used separately.
ForEach isn't a List, it only provides views based on a RandomAccessCollection of some data type. However a List, a Grid, or a stack can be configured using a ForEach.
See Editing Grids to learn how to organize and edit grids.
A List with a ForEach that’s configured with the onDelete(perform:) or onMove(perform:) modifier will provides controls to delete or move list items while in edit mode.
See EditButton for examples on how to reorder a List.