【问题标题】:Not receiving event for updated @Published未收到更新的@Published 事件
【发布时间】:2020-06-30 09:25:35
【问题描述】:

我正在尝试稍微了解一下 Combine,但遇到了问题,无法解决:

我得到了这个数据源

class NoteManager: ObservableObject, Identifiable {
  @Published var notes: [Note] = []
  var cancellable: AnyCancellable?
  init() {
    cancellable = $notes.sink(receiveCompletion: { completion in
      print("receiveCompletion \(completion)")
    }, receiveValue: { notes in
      print("receiveValue \(notes)")
    })
  }
}

这里使用的是:

struct ContentView: View {
  @State var noteManager: NoteManager
    
      var body: some View {
        
        VStack {
          NavigationView {
            VStack {
              List {
                ForEach(noteManager.notes) { note in
                  NoteCell(note: note)
                }
              }
...

我可以在这里更改值:

    struct NoteCell: View {
      @State var note: Note
      
      var body: some View {
        NavigationLink(destination: TextField("title", text: $note.title)
...

无论如何 - 在更改值后我没有收到 receiveValue 事件(这也正确反映在 ui 中)。 receiveValue 仅在初始设置时调用 - 是否有其他方法可以接收更新字段的事件?

添加:

struct Note: Identifiable, Codable {
  var id = UUID()
  var title: String
  var information:  String
}

【问题讨论】:

  • @Asperi 除非@​​987654327@ 本身是ObservableObject,其title@Published
  • 在 Note 和 NoteManager 中使用 @ObservedObject 而不是 @State 也会有所帮助。
  • @Michael,你能展示一下 Note 是什么吗?
  • note 是一个结构 - 因此 @ObservedObject 不是一个选项 - 我需要将其设为一个类以检测更改吗?
  • 我在问题中添加了 Note 结构

标签: swift swiftui combine


【解决方案1】:
  1. 制作经理观察对象(因为它是可观察对象的设计对)
    struct ContentView: View {
      @ObservedObject var noteManager: NoteManager
  1. 通过绑定使单元格编辑原始注释(因为注释是结构)
    struct NoteCell: View {
      @Binding var note: Note
  1. 按预测值将注释直接从经理(单一事实来源)转移到单元格(编辑器)
    ForEach(Array(noteManager.notes.enumerated()), id: \.element) { i, note in
      NoteCell(note: $noteManager.notes[i])
    }

【讨论】:

    猜你喜欢
    • 2021-09-07
    • 2021-12-29
    • 2021-10-14
    • 2020-04-30
    • 1970-01-01
    • 2022-01-04
    • 2019-09-11
    • 2017-06-25
    • 2020-11-12
    相关资源
    最近更新 更多