首页 > 解决方案 > 未收到更新的@Published 事件

问题描述

我正在尝试稍微了解一下 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
}

标签: swiftswiftuicombine

解决方案


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

推荐阅读