here I have two classes. When I add a Person the view updates, but when I add a TodolistItem, the view isn't updating. When I press the Button for adding a todo and then press the button for adding a person, the person and the todo is there. So the button works properly, the only problem is the refresh of my view.
That's my code:
import SwiftUI
class Person: Identifiable, ObservableObject {
let id = UUID()
@Published var name: String
@Published var item: [TodolistItem]
init(name: String, item: [TodolistItem]) {
self.name = name
self.item = item
}
}
class TodolistItem: Identifiable, ObservableObject {
@Published var todoName: String
@Published var priority: String
init(todoName: String, priority: String) {
self.todoName = todoName
self.priority = priority
}
}
struct Todolist: View {
@State private var personen: [Person] = [
Person(name: "Michi", item: [
TodolistItem(todoName: "Reifenwechsel", priority: "Niedrig"),
TodolistItem(todoName: "Irgendwas", priority: "Mittel")
]),
Person(name: "Tina", item: [
TodolistItem(todoName: "Haushalt", priority: "Dringend!")
])
]
let navTitle: String
var body: some View {
NavigationStack {
List {
ForEach(personen) { person in
Section(person.name) {
ForEach(person.item) { item in
SubView(item: item)
}
.onDelete { offSet in
person.item.remove(atOffsets: offSet)
}
Button {
let newItem = TodolistItem(todoName: "Opfer", priority: "Dringend!!")
withAnimation {
person.item.append(newItem)
person.objectWillChange.send()
}
} label: {
HStack {
Image(systemName: "plus")
Text("Neues Todo hinzufügen")
}
}
}
}
}
.listStyle(.insetGrouped)
}
.navigationTitle(navTitle)
.navigationBarItems(trailing:
Button(action: { addItem() }, label: {
Image(systemName: "plus.circle")
})
)
}
func addItem() {
let newItem = Person(name: "Test", item: [TodolistItem(todoName: "Test1", priority: "Niedrig")])
personen.append(newItem)
}
}
struct SubView: View {
@State private var isDone: Bool = false
@ObservedObject var item: TodolistItem
var body: some View {
VStack {
HStack {
Text(item.todoName)
Spacer()
Text(item.priority)
.padding(.horizontal)
Button(action: {
isDone.toggle()
}, label: {
Image(systemName: isDone ? "checkmark.circle.fill" : "checkmark.circle")
})
}
}
}
}
Maybe its just a small Mistake, but I'm not getting it.