TEAM LICENSES: Save money and learn new skills through a Hacking with Swift+ team license >>

assign properties to buttons in a grid

Forums > SwiftUI

this seems like it should not be so hard, and yet...

so I have a grid of buttons, say, 3x3 for simplicity. In each square, there's a button:

ForEach(0..<gridSize, id: \.self) { row in
                GridRow {
                    ForEach(0..<gridSize, id: \.self) {col in
                        if (row + col).isMultiple(of: 2) {
                        GeometryReader { proxy in
                                Rectangle()
                                    .foregroundColor(.gray)
                                    .overlay(Text("\(row),\(col)"))
                                    .border(Color.black)
                                    .bold()

                                Button (action: {
                }, label: {
                                    Text("some text")
                                        .frame(width: proxy.frame(in: .global).width,height: proxy.frame(in: .global).height)
                 }

what I want to do is assign a set of properties to the button, such as a UUID, a name, and a set of coordinates that correspond to its grid location. Here's a struct I built, but it can be a class too, i'm not tied to either:

struct buttonData {
    var buttonID = UUID()
    var buttonContents: String
    var buttonCoords: (buttonX: Int, buttonY: Int)
}

so now I have the data I care about (and I'm not tied to this method either, if someone has a better way, cool).

What I am utterly failing it is assigning those properties to the button in a way that lets me reference it on a click. I can use a state var or a stateobject var, but I get one version of that, and I need anywhere between 9 and 100 depending on grid size (the user can change the grid size from 3x3 to 10x10)

At some point, I need to be able to reference the buttons from an outside function, hence the buttonID and buttonCoords, but I can't even ASSIGN the values much less use them.

any help would be appreciated.

(tl;dr of backstory - it's for a project building an SOS game where you try to build "SOS" on a game board)

what I have so far in "completed" form is at: https://github.com/johncwelch/SOS-Swift

thanks!

2      

Hacking with Swift is sponsored by String Catalog.

SPONSORED Get accurate app localizations in minutes using AI. Choose your languages & receive translations for 40+ markets!

Localize My App

Sponsor Hacking with Swift and reach the world's largest Swift community!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.