1

i have this code. it is pretty simple. i change the rows by one when tapping the button.

but only the output in the line "works" works, the other one always is 0.

What am i doing wrong!?

you can copy and paste the code to reproduce the error.

class GlobalData : ObservableObject {

    @Published var rows : Int = 0
}


struct ContentView: View {

    @ObservedObject var globalData = GlobalData()

    var body: some View {
        VStack {
            Text("\(self.globalData.rows)") // works...
            ForEach (0..<4) { y in
                HStack () {
                    ForEach (0..<3) { x in

                        ForEach (0..<3) { index -> Text in
                            Text("\(self.globalData.rows)") // shows always 0
                        }
                    }
                }
            }
            Button(action: {
                self.globalData.rows = self.globalData.rows + 1
            }) {
                Text("Increase rows")
            }
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

1 Answer 1

2

The reason is in constant ForEach(range). If supposed anything changed inside ForEach use dynamic data sequence.

Here is a solution for your case. Tested with Xcode 11.4 / iOS 13.4.

struct ContentView: View {

    @ObservedObject var globalData = GlobalData()

    var body: some View {
        VStack {
            Text("\(self.globalData.rows)") // works...
            ForEach (Array(0...3), id: \.self) { y in
                HStack () {
                    ForEach (Array(0...2), id: \.self) { x in

                        ForEach (Array(0...2), id: \.self) { index -> Text in
                            Text("\(self.globalData.rows)") // works ...
                        }
                    }
                }
            }
            Button(action: {
                self.globalData.rows = self.globalData.rows + 1
            }) {
                Text("Increase rows")
            }
        }
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.