0

I have the following simple ContentView:

struct ContentView: View {

@State private var matrix = [BoxModel(id: 0), BoxModel(id: 1), BoxModel(id: 2)]
@State private var chosen = BoxModel(id: -1)

var body: some View {
    NavigationView {
        GeometryReader { geometry in
            ScrollView {
                VStack {

                    let columns = [GridItem(.fixed(50), spacing: 0),
                                     GridItem(.fixed(50), spacing: 0),
                                     GridItem(.fixed(50), spacing: 0)]
                    

                    LazyVGrid(columns: columns, spacing: 0 ) {
                        ForEach(matrix) { box in
                            Button {
                                chosen = box
                            } label: {
                                Text("\(box.number)")
                            }
                        }
                    }
                    .padding()
                    Button {
                        chosen.number = 5
                    } label: {
                        Text("Click Me")
                    }
                }
            }
        }
    }
}
}

where the BoxModel is an object like this:

struct BoxModel: Codable, Identifiable, Hashable {
    var id: Int
    var number: Int
}

When the button is pressed I want the "box" to be updated with the new number. But I want to do this without using the index. I know that if I get the index of the box, I can do something like matrix[0].number = 5 and it'll work.

Is this possible?

1 Answer 1

1

Your code shows boxes that are contained in the matrix array, while you have also created chosen which is a completely different instance.

You change chosen to store 5 in the "number" property, and I bet it's changing, but you are still only showing in the UI the instances of the boxes that are inside the matrix array, whatever happens to chosen will not be seen on the screen.

You need to completely drop the chosen variable, and have a button that changes each instance of "box" that is in the matrix. You might want to move your code inside the ForEach to another view too; that view would have a @State var of type BoxModel of its own, so you can see the changes as they happen.

Sign up to request clarification or add additional context in comments.

3 Comments

Could you elaborate on moving the code to a different view? Do you have a small example?
You can see an example in this answer. Look at the StudentButton view: it has its own @State property.
But how does the grid tell the button which square is tapped?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.