Group Group Group Group Group Group Group Group Group

Ch 9 State and Binding

In the discussion about State and binding of numberOfAnswered between the ScoreView and ChallengeView… The book had suggested that only the variable in ChallengeView will get updated. However, when i tried this in code, i’m getting the opposite result (only Scoreview is getting updated, not ChallengeView). So i’m a little confused… I’m running this with Xcode 11.6 and Xcode 12 beta 4 with the same result… am i doing soemthing wrong?

ChallengeView

 struct ChallengeView: View {
        let challengeTest: ChallengeTest
        @State var showAnswers = false
        @State var numberOfAnswered = 0
    
  var body: some View {
    VStack {
        Button(action: {
            self.showAnswers = !self.showAnswers
            self.numberOfAnswered += 1
        }) {
            QuestionView(question: challengeTest.challenge.question)
                .frame(height:300)
            
            if showAnswers {
                Divider()
                
                ChoicesView(challengeTest: challengeTest)
                    .frame(height:300)
                    .padding()
            }
        }
        ScoreView(numberOfAnswered: numberOfAnswered, numberOfQuestions: 5)
        Text("Challenge VIew Counter: \(numberOfAnswered)")

    }
  }
}

ScoreView

   struct ScoreView: View {
    @State var numberOfAnswered: Int
    let numberOfQuestions : Int
    
    var body: some View {
        HStack {
            Button(action: {
                self.numberOfAnswered += 1
                Text("\(self.numberOfAnswered)/\(numberOfQuestions)")
                .font(.caption)
                .padding(4)
                Text("Score VIew Counter: \(numberOfAnswered)")

            Spacer()
            }
        }
    }
}

never mind… i was clicking on the wrong button… :sweat_smile:

Cool :slight_smile: so it works as expected, right?

1 Like

@abnopanda Do you still have issues with this?