|
I'm working on a project for a class that requires building a grid. I found some really good tutorials on Grids in swiftui, including from here that really helped, but I need to be able to update the size of the grid based on a selection in a dropdown. What i've not been able to find is how to change the size of the grid. So for example, with this grid:
what I need to do is when the value of gridSize changes, to redraw the grid with the new value. Any help on that would be greatly appreciated |
|
Hi! Will this solve your challenge?
you can also shrink your code a little bit by using ternary operator like so
instead of if else |
|
I figured this out in another post in the forum just before I saw your reply. I didn't have the id: .self identifier, so swiftui was very confused. I appreciate the reply though, it showed me the same thing as the other post, so thank you very much! I still have to put a button in each grid item, and right now the code may be verbose, but I understand it well. The teacher for the course doesn't know swift at all (just Java and eclipse is such a NO), so I'm not real worried he'll fuss at me about verbosity ;-) |
|
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
} 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. |
SAVE 50% All our books and bundles are half price for Black Friday, so you can take your Swift knowledge further without spending big! Get the Swift Power Pack to build your iOS career faster, get the Swift Platform Pack to builds apps for macOS, watchOS, and beyond, or get the Swift Plus Pack to learn advanced design patterns, testing skills, and more.
This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.
All interactions here are governed by our code of conduct.
Link copied to your pasteboard.