Post

Replies

Boosts

Views

Activity

Reply to Why is @Binding not behaving as I expect here?
FYI—The following code works using an ObservableObject pattern—just curious why the @Binding doesn't work? import SwiftUI // MARK: - Model final class Model: ObservableObject {       let title: String       @Published   var count: Int       init(title: String, count: Int) {     self.title = title     self.count = count   } } extension Model: Identifiable {   var id: String {     title   } } // MARK: - StateProvider final class StateProvider: ObservableObject {       @Published   var data: [Model] = [     Model(title: "Elephant", count: 3),   ] } // MARK: - Detail View struct DetailView: View {       @EnvironmentObject   private var model: Model       var body: some View {     ScrollView {       Text(model.title)         .font(.title)       Stepper(model.count.formatted()) {         model.count += 1       } onDecrement: {         model.count -= 1       }       .padding()     }   } } // MARK: - List View struct Row: View {       @EnvironmentObject   private var model: Model       var body: some View {     HStack {       Text(model.title)       Spacer()       Text(model.count.formatted())     }   } } struct ContentView: View {       @StateObject   private var stateProvider = StateProvider()       var body: some View {     NavigationStack {       List {         ForEach(stateProvider.data) { model in           NavigationLink {             DetailView()               .environmentObject(model)           } label: {             Row()               .environmentObject(model)           }         }       }     }   } } // MARK: - Preview struct ContentView_Previews: PreviewProvider {   static var previews: some View {     ContentView()       .preferredColorScheme(.dark)   } } Now I think about it, the source of truth when using the @Binding is the final class StateProvider: ObservableObject {}, right? And since the DetailView doesn't reference the stateProvider, the DetailView doesn't get reloaded when the Model updates? Now, by using an ObservableObject for the Model, the source of truth changes to being the Model instead of the state provider, therefore the view responds to updates? Could someone please verify if this line of thinking is correct? Thanks!
Topic: UI Frameworks SubTopic: SwiftUI Tags:
Aug ’22