0

Newbie here. I am creating a quiz app. Unlike most of the examples, every question is in a separate view. I'd like to keep the score and show it at the end.

Example:

struct questionOne: View {
    @State var isSelected = false
    var body: some View {
       GeometryReader { geometryProxy in
        VStack(alignment: .center) {

            TRpic().cornerRadius(10)

            Text("What's the capital of Turkey?")
                .font(.title)

            Spacer()

           Button(action: {self.isSelected.toggle()}) {
               Text("Istanbul")
           } .buttonStyle(SelectedButtonStyleFalse(isSelected: self.$isSelected))

           Button(action: {self.isSelected.toggle()}) {
                Text("Ankara")
            }.buttonStyle(SelectedButtonStyle(isSelected: self.$isSelected))

           Button(action: {self.isSelected.toggle()}) {
                Text("Athens")

            } .buttonStyle(SelectedButtonStyleFalse(isSelected: self.$isSelected))

             Spacer()

            NavigationLink(destination: questionTwo()) {
              VStack {
                Text("Next Question")

               Adview().frame(width: 150, height: 50)
             }
          }
       }
    }
  }
}


struct SelectedButtonStyle: ButtonStyle {

    @Binding var isSelected: Bool

    public func makeBody(configuration: Self.Configuration) -> some View {
        configuration.label
            .padding(20)
            .foregroundColor(.white)
            .background(isSelected ? Color.green : Color.gray)
            .cornerRadius(10.0)
    }
}


struct SelectedButtonStyleFalse: ButtonStyle {

    @Binding var isSelected: Bool

    public func makeBody(configuration: Self.Configuration) -> some View {
        configuration.label
            .padding(20)
            .foregroundColor(.white)
            .background(isSelected ? Color.red : Color.gray)
            .cornerRadius(10.0)
    }
}

I have two button styles: SelectedButtonStyle (for the true answer) and SelectedButtonStyleFalse (for the false answer)

All 50 questions (views) are connected via NavigationView. And in the end, I want to show the total score in a separate view. For example "You have scored 35/50".

Thanks!

Andrew
  • 26,706
  • 9
  • 85
  • 101
I Kaya
  • 417
  • 5
  • 22

2 Answers2

3

You can use @EnvironmentObject. All you have to do it create a class like this:

import Foundation

class GameStatus: ObservableObject {
    @Published var score: Int = 0
}

Then in your struct add @EnvironmentObject var gameStatus: GameStatus

Finally, you need to trigger update on the score, just do

self.gameStatus.answers += 1
Bartosz
  • 378
  • 3
  • 11
1

Check out Three Ways To Do The Same Job for 3 examples of how to share data between views.

BioPhysic
  • 29
  • 2