Swift 未接收更新@Published的事件

Swift 未接收更新@Published的事件,swift,swiftui,combine,Swift,Swiftui,Combine,我试着理解一下组合,但遇到了一个问题,我无法理解: 我得到了这个数据源 class NoteManager: ObservableObject, Identifiable { @Published var notes: [Note] = [] var cancellable: AnyCancellable? init() { cancellable = $notes.sink(receiveCompletion: { completion in print(&qu

我试着理解一下组合,但遇到了一个问题,我无法理解:

我得到了这个数据源

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
}
  • 使管理者成为可观察对象(因为它是可观察的设计对)
  • 通过绑定使单元格编辑原始注释(注释为结构)
  • 按投影值将注释直接从manager(单一真实来源)传输到单元格(编辑器)

  • @Asperi当然,除非
    Note
    本身是一个
    observeObject
    ,其
    标题
    @已发布的
    ,否则对Note和NoteManager使用
    @observeObject
    而不是
    @State
    ,也会有所帮助。@Michael,你能告诉我什么是Note吗?Note是一个结构-因此@ObservedObject不是一个选项-我需要把它变成一个类来检测变化吗?我在问题中添加了Note结构
        struct ContentView: View {
          @ObservedObject var noteManager: NoteManager
    
        struct NoteCell: View {
          @Binding var note: Note
    
        ForEach(Array(noteManager.notes.enumerated()), id: \.element) { i, note in
          NoteCell(note: $noteManager.notes[i])
        }