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