我一直在尝试一个简单的功能来将新条目添加到列表中。该视图只会添加一个新生成的。项目(不需要用户输入)。
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:如果 @ObservedObject 是 UIViewController 的子类,则视图内容不会重新加载。这是一个错误还是我错过了什么? https://stackoverflow.com/questions/57702108/swiftui-view-content-not-reloading-if-observedobject-is-a-subclass-of-uiviewco和这里:SwiftUI @Binding 不刷新视图 https://stackoverflow.com/questions/57127878/swiftui-binding-doesnt-refresh-view