Home > AI > IOS > SwiftUI >

@StateObject

Example: This code shows when the variable @State changed, the view will get re-rendered so that the value of @Observed ger reinitiated. To save the value, change @ObservedObject to @StateObject that the value persists even if the CounterView get destructed and ContentView got re-rendered.

import SwiftUI

struct CounterView: View {
    // change it to @StateObject will solve the problem
    @ObservedObject var model = CounterViewModel()
    
    var body: some View {
        VStack {
            Text("CounterView's count")
            Text(String(model.count))
        }
        .padding()
        .background(Color.orange)
        .onTapGesture {
            model.count += 1
        }
        
    }
}


class CounterViewModel: ObservableObject {
    @Published var count: Int = 0
}


struct ContentView: View {
    @State var count: Int = 0
    
    var body: some View {
        HStack{
            VStack {
                Text("ContentView's count")
                Text(String(count))
            }
            .padding()
            .background(Color.green)
            .onTapGesture {
                self.count += 1
            }
            
            CounterView()
           
        }
        
    }
}

Leave a Reply