TiN
TiN

Reputation: 389

SwiftUI Childview not not refreshing on @Binding update

I have a conditional view based on 2 binding vars in MyBootomSheet. Idea is, show detail view if an item is selected in parent view, else show list of items.

ParentView has the logic to select/unselect item. The code works as expected for the first time. But once an item is selected in the parent view the view never gets updated ever again, even after another item selected or item is unselected.

Any idea how this can be resolved ?

TIA!

struct ParentView: View {
    @StateObject var dataSource = MapViewSource()
    @State var selectedItem:SomeModel? = nil
    
    var body: some View {
     //
    }.bottomSheet() {
    MyBottomSheet(items:self.$dataSource.items, selectedItem:self.$selectedItem)
    }
}

struct MyBottomSheet: View {
    @Binding var items:[SomeModel]
    @Binding var selectedItem:SomeModel?
    
    var body: some View {
        if self.selectedItem != nil {
            ItemDetail(item: self.selectedItem!)
        }
        else {
            List(self.items id: \.itemId) { item in 
               ItemRow(item: item)
            }
        }
    }
}

Upvotes: 0

Views: 70

Answers (1)

nOk
nOk

Reputation: 3439

State uses Binding for childviews but StateObject needs an ObservedObject:

class SomeObservableObject: ObservableObject {
    // if this wasn't published, then the view wouldn't update when only changing the value
    @Published var value: String
    
    init(_ value: String) {
        self.value = value
    }
}

struct ParentView: View {
    @State var state: String = "This is a State"
    @StateObject var stateObject: SomeObservableObject = .init("This is an ObservableObject")
    
    var body: some View {
        ChildView(state: $state, stateObject: stateObject)
    }
}

struct ChildView: View {
    @Binding var state: String
    @ObservedObject var stateObject: SomeObservableObject
    
    var body: some View {
        VStack {
            Text("State: \(state)")
            Text("StateObject: \(stateObject.value)")
        }
    }
}
``

Upvotes: 1

Related Questions