Reputation: 1749
I've been trying a simple feature to add new entries to a List. The View will just add a new generated. item (no need for user input).
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: ""))
}
}
This used to work in previous betas, but for some reason it's not working anymore. When I click on Add, the App does call the add()
function and adds the new entry to the array, but the View is not updated at all.
These are the support classes:
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
And the support views:
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)
}
}
I've found someone with a problem that looks a bit related here: SwiftUI: View content not reloading if @ObservedObject is a subclass of UIViewController. Is this a bug or am I missing something? and here: SwiftUI @Binding doesn't refresh View
Upvotes: 2
Views: 1786
Reputation: 1184
The problem is that when you implemented your own ObservableObject you used the wrong publisher. The ObservableObject protocol creates the objectWillChange publisher but you never use it so that SwiftUI is never informed that anything has changed.
class Person: ObservableObject, Identifiable {
let id: Int
@Published
var name: String
init(id: Int, name: String) {
self.id = id
self.name = name
}
}
I haven't run that through the compiler so there might be some typos.
You don't have to use @Published but for a simple case like yours it's easier. Of course you need to update your other class as well.
Another small thing, id is required to never change, List et al. use it to connect your data with the view they create.
Upvotes: 2