To update the grid size based on a selection in a dropdown in SwiftUI, you can use a Picker to allow the user to select the grid size, and then use the onChange modifier to redraw the grid whenever the gridSize changes. Here's how you can modify your code to achieve this:
swift
Copy code
struct ContentView: View {
@State private var gridSize = 5
let gridSizes = [3, 4, 5, 6, 7] // Define the available grid sizes in your dropdown
var body: some View {
VStack {
Picker("Grid Size", selection: $gridSize) {
ForEach(gridSizes, id: \.self) { size in
Text("\(size)")
}
}
.pickerStyle(SegmentedPickerStyle())
.onChange(of: gridSize) { _ in
// Redraw the grid when gridSize changes
}
Grid(horizontalSpacing: 0, verticalSpacing: 0){
ForEach(0..<gridSize) { row in
GridRow {
ForEach(0..<gridSize) {col in
if (row + col).isMultiple(of: 2) {
Rectangle()
.fill(Color.black)
} else {
Rectangle()
.fill(Color.white)
}
}
}
}
}
}
}
}
In this code, we use a Picker with a segmented style to allow the user to select the grid size. The onChange modifier observes changes in the gridSize state variable, and whenever it changes, you can add the logic to redraw the grid with the new size.