UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

Published Variable does not change on different views.

Forums > Swift

The published variable (allTimeScore) does not change on the view "Me" but does on the "home" view. How do I make it chnage on both?

class SavedVariables: ObservableObject {
    @Published var allTimeScore = 0
   @Published var introductionShowed = true
}

Home View:

struct Home: View {
    @StateObject var savedVariables = SavedVariables()

    @State private var number1 = 0
    @State private var number2 = 0
    @State private var answer = 0

    @State private var givenAnswer = 0

    @State private var alertTitle = ""

    var body: some View {
        NavigationView{
            VStack{
        Text("What is \(number1) x \(number2)")
                TextField("Enter your Answer:", value: $givenAnswer, formatter: NumberFormatter())

                Button("Submit"){
                    if (givenAnswer == answer){
                        savedVariables.allTimeScore += 10
                        number1 = Int.random(in: 1..<12)
                        number2 = Int.random(in: 1..<12)
                        answer = number1 * number2

                    } else {
                        number1 = Int.random(in: 1..<12)
                        number2 = Int.random(in: 1..<12)
                        answer = number1 * number2
                    }
                }.padding(.horizontal).background(.blue).cornerRadius(20).font(.title).foregroundColor(.white)
                Text("Answer\(answer)")
                Text("All Time:\(savedVariables.allTimeScore)")
            }.navigationTitle("Times Tables")
                .toolbar{
                    Button("Start"){
                        savedVariables.allTimeScore = 0
                        number1 = Int.random(in: 1..<12)
                        number2 = Int.random(in: 1..<12)
                        answer = number1 * number2
                    }.font(.title)
                }
    }
}
}

struct Home_Previews: PreviewProvider {
    static var previews: some View {
        Home()
    }
}

Me View:

struct Me: View {
    @ObservedObject var savedVariables = SavedVariables()
    var body: some View {

        Text("Your Overall Score is: \(savedVariables.allTimeScore)")
    }
}

struct Me_Previews: PreviewProvider {
    static var previews: some View {
        Me()
    }
}

ContentView:

struct ContentView: View {
    @StateObject var savedVariables = SavedVariables()
    var body: some View {
        TabView{
           Home()
                .tabItem{
                    Image(systemName: "house.circle")
                    Text("Home")
                }
                    Me()
                        .tabItem {
                            Image(systemName: "person.circle")
                            Text("Me")
                        }
        }
    }
}

3      

hi,

i am not sure where these view are in your app ... neither appears to be a subview of the other, not does either navigate to the other ... but your "Home" and "Me" views have independent references to their own saved variables.

if these views are independent (say they occur as subviews in a TabView), then the definition of the @StateObject should appear outside the views (e.g., in the TabView) and be passed in to each of the "Home" and "Me" views as @ObservedObject references.

in general, when you see an @ObservedObject reference that sets its value:

@ObservedObject var savedVariables = SavedVariables() // this sets the value of the object

then you're probably doing something wrong.

hope that helps,

DMG

3      

@delawaremathguy

It is connect by a tabView sorry for not including the content View:

struct ContentView: View {
    var body: some View {
        TabView{
           Home()
                .tabItem{
                    Image(systemName: "house.circle")
                    Text("Home")
                }
                    Me()
                        .tabItem {
                            Image(systemName: "person.circle")
                            Text("Me")
                        }
        }
    }
}

3      

You created two different SavedVariable() GameVariables() objects.
You give them the same name, you tell Swift that both are Observable objects, but they are two different objects.

This is why when one changes, the other is not updated.

You need to take a step back, and think about your application's architecture.
Q: Where should you create the GameVariables() object?
A: You should create it somewhere central to all your game's views.

Q: How do I see the GameVariables() object in a sub view?
A: You can pass in a reference to the class object via the view's initializer.

Q: Can I pass in a reference to the GameVariable() object to more than one view?
A: Sure!

Q: What if code changes one of the GameVariable() properties? Will the other views see it and respond?
A: This is the power of ObservedObject! Yes, each view will monitor their common, shared GameVariable() object. If anything in that object changes, it can trigger the view to redraw itself.

See this forums post which answers the same question:

Observable Objects in Tab Views

3      

Hacking with Swift is sponsored by Essential Developer

SPONSORED Join a FREE crash course for mid/senior iOS devs who want to achieve an expert level of technical and practical skills – it’s the fast track to being a complete senior developer! Hurry up because it'll be available only until April 28th.

Click to save your free spot now

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

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

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.