我一直在尝试一个简单的功能,将新条目添加到列表中。视图将只添加一个新生成的。项目(不需要用户输入)。
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时,应用程序会调用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. Is this a bug or am I missing something?和这里:SwiftUI @Binding doesn't refresh View
发布于 2019-08-31 17:04:23
问题是,当您实现自己的ObservableObject时,您使用了错误的发布者。ObservableObject协议创建了objectWillChange发布程序,但您从未使用过它,因此SwiftUI永远不会被告知发生了任何更改。
class Person: ObservableObject, Identifiable {
let id: Int
@Published
var name: String
init(id: Int, name: String) {
self.id = id
self.name = name
}
}我没有通过编译器运行它,所以可能会有一些打字错误。
您不必使用@Published,但对于像您这样的简单案例来说,它会更简单。当然,你也需要更新你的其他类。
另一件小事,id需要永远不变,List等人。使用它将您的数据与它们创建的视图连接起来。
https://stackoverflow.com/questions/57732284
复制相似问题