swift - 未收到更新的@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])
}
推荐阅读
- amazon-web-services - AWS SNS 订阅与 lambda 函数的触发器?
- html - 平滑悬停动画在随机网站上有效,但在我的网站上无效,为什么?
- swift - Firebase 数据库不会快速存储(写入)数据
- python - 使用 Python 进行异步和等待
- swift - 使用常量设置 UILabel 的文本
- python - 尝试在 Python 中反转输出
- google-sheets - 谷歌表格数组公式sumifs重复数组中所有值的第一个值
- python - 从验证码中删除曲线
- javascript - 使用 JSX 时必须在范围内获取“React”
- ruby-on-rails - rake 资产预编译时出现 capistrano 3 错误