蘇哲聖
蘇哲聖

Reputation: 795

SwiftUI state not consistent

Here is my code:

import SwiftUI
struct ContentView: View {
    let countView = CountView()
    var body: some View {
        VStack {
            countView
            Text("My Count: \(countView.count)")
            Button("Show My Count"){print("\(self.countView.count)")}
        }
    }
}
struct CountView: View {
    @State var count: Int = 1
    var body: some View {
        VStack {
            Button("Increase count"){self.count += 1}
            Text("Count = \(count)")
        }
    }
}
struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

It happens that MyCount = and Count = show different value after count increased. That always shows MyCount = 1 no mater what Count = is.

Am I doing wrong? How to synchronize MyCount value?

Upvotes: 0

Views: 54

Answers (1)

Sweeper
Sweeper

Reputation: 271390

You should not access another view's @State:

Text("My Count: \(countView.count)")

This is a giant red flag indicating that you are doing something wrong. You need a @Binding here.

Instead of making CountView "own" the count, ContentView should own the count because it needs to show it in its Text. ContentView should tell CountView to count with ContentView.count using a @Binding:

struct ContentView: View {
    @State var count = 1
    var body: some View {
        VStack {
            CountView(count: $count)
            Text("My Count: \(count)")
            Button("Show My Count"){print("\(self.count)")}
        }
    }
}
struct CountView: View {
    @Binding var count: Int
    var body: some View {
        VStack {
            Button("Increase count"){self.count += 1}
            Text("Count = \(count)")
        }
    }
}

Upvotes: 1

Related Questions