iOS SwiftUI:子视图@ObservedObject中的数据流

时间:2019-10-12 10:25:47

标签: ios swift swiftui combine

我的应用程序中存在更新问题。 我不太了解子视图之间的数据流是怎么回事。

这是我当前的结构

  • ViewModel :ObsebsrvableObject

  • MainView 和ObservedObject(viewModel)

    • ChildView ,其中包含MainView被观察对象的列表(只是列表作为普通数组传递-不可绑定)
      • NephewView ,列表仍作为普通数组传递给childView

发生了什么事

每次修改列表时,MainView更新都会触发ChildView的新重建,但NephewView不会更新

我想拥有的东西:

每次观察对象更新时,我想更新Main,Child和NephewView视图。

问题:

我不明白为什么重建子视图时,侄子不重建。

示例代码

class ViewModel: ObservableObject {

    let userData = UserData.shared

    var canceller: AnyCancellable?

    @Published var items: [Items]


    init() {
      items = []
      canceller = userData.objectWillChange
        .throttle(for: 5, scheduler: RunLoop.main, latest: true)
        .sink(receiveCompletion: { data  in
            DispatchQueue.main.async { [weak self] in
                guard let self = self else { return }
                self.items = data.items
            }
        },
        receiveValue: { _ in
            DispatchQueue.main.async { [weak self] in
                guard let self = self else { return }
                self.items = data.items
            }
        })
   }
 }

struct MainView: View {

  @ObservedObject var model = ViewModel()


  var body: some View {
      ChildView(items: model.items)
  }
}

struct ChildView: View {

  let items: [Items]


  var body: some View {
      NephewView(items: items)
  }
}

struct NephewView: View {

  let items: [Items]

  var body: some View {
      List...
  }
}

接收器正常工作,只是UI部分没有更新。 也许我更新发布者的方式是错误的?

1 个答案:

答案 0 :(得分:0)

您的MainView

 ChildView(items: $model.items)

您的ChildView

struct ChildView: View {
  @Binding let items: [Items]
  var body: some View {
     List { 
     ForEach(self.items) { item in
           NephewView(items: item)
          }
        }
      }
    }

您的NephewView

struct NephewView: View {
  @Binding let items: item

  var body: some View {
    // Your view logic goes here with single item
  }
}