我一直在尝试一个简单的功能来将新条目添加到列表中。视图只会添加一个新生成的。项目(无需用户输入)。
struct PeopleList: View {
@ObservedObject var people: PersonStore
var body: some View {
NavigationView {
VStack {
Section {
Button(action: add) {
Text("Add")
}
}
Section {
List {
ForEach(people.people) { person in
NavigationLink(destination: PersonDetail(person: person)) {
PersonRow(person: person)
}
}
}
}
}
}
.navigationBarTitle(Text("People"))
.listStyle(GroupedListStyle())
}
func add() {
let newID = (people.people.last?.id ?? 0) + 1
self.people.people.append(Person(id: newID, name: ""))
}
}
这曾经在以前的测试版中工作,但由于某种原因它不再工作了。当我单击添加时,应用程序确实调用了该add()
函数并将新条目添加到数组中,但视图根本没有更新。
这些是支持类:
class PersonStore: ObservableObject {
var people: [Person] {
willSet {
willChange.send()
}
}
init(people: [Person] = []) {
self.people = people
}
var willChange = PassthroughSubject<Void, Never>()
}
class Person: ObservableObject, Identifiable {
var id: Int = 0 {
willSet {
willChange.send()
}
}
var name: String {
willSet {
willChange.send()
}
}
init(id: Int, name: String) {
self.id = id
self.name = name
}
var willChange = PassthroughSubject<Void, Never>()
}
#if DEBUG
let data = [
Person(id: 1, name: "David"),
Person(id: 2, name: "Anne"),
Person(id: 3, name: "Carl"),
Person(id: 4, name: "Amy"),
Person(id: 5, name: "Daisy"),
Person(id: 6, name: "Mike"),
]
#endif
以及支持意见:
struct PersonRow: View {
@ObservedObject var person: Person
var body: some View {
HStack {
Image(systemName: "\(person.id).circle")
Text(person.name)
}.font(.title)
}
}
struct PersonDetail: View {
@ObservedObject var person: Person
var body: some View {
HStack {
Text("This is \(person.name)")
}.font(.title)
}
}
我发现有人有一个看起来有点相关的问题: SwiftUI: View content not reloading if @ObservedObject is a subclass of UIViewController。这是一个错误还是我错过了什么? 在这里: SwiftUI @Binding 不刷新视图