【问题标题】:SwiftUI Childview not not refreshing on @Binding updateSwiftUI Childview 在@Binding 更新时不刷新
【发布时间】:2021-09-19 05:42:29
【问题描述】:

我有一个基于 MyBootomSheet 中的 2 个绑定变量的条件视图。 想法是,如果在父视图中选择了一个项目,则显示详细视图,否则显示项目列表。

ParentView 具有选择/取消选择项目的逻辑。 该代码首次按预期工作。但是一旦在父视图中选择了一个项目,视图就永远不会再更新,即使在另一个项目被选中或项目被取消选择之后。

知道如何解决这个问题吗?

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)
            }
        }
    }
}

【问题讨论】:

  • 使用 ObservedObject 或 EnvironmentObject 传递 ObservableObject vs Binding

标签: swiftui


【解决方案1】:

StateBinding 用于子视图,但 StateObject 需要 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)")
        }
    }
}
``

【讨论】:

    猜你喜欢
    • 2020-04-05
    • 2019-11-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-22
    • 2022-06-23
    • 1970-01-01
    相关资源
    最近更新 更多