未收到更新的@Published 事件
Not receiving event for updated @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
}
- 制作经理观察对象(因为它是可观察对象的设计对)
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])
}
我想稍微了解一下 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
}
- 制作经理观察对象(因为它是可观察对象的设计对)
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])
}