Hello guys, I'm really starting to hating SwiftUI cause for me it never works when i think it should.. But maybe I'm just not good enough.
I'm trying to update a simple list based on an array situated on the model, but the view won't update. Here is the relevant code:
The cose might miss some parenthesis cause it is not copied exactly, only the needed parts for you to understand.
Thank you to anyone who might help me!
struct Model {
var ticket: [Item] = []
}
class Controller: ObservableObject {
@Published var model = Model()
var viewContext = PersistenceController.shared.container.viewContext
var ticketItems: [Item] {
get {
posViewModel.ticket
}
}
func addItemToTicket(withName name: String, price: Double) {
let item = Item(context: viewContext)
item.name = name
item.price = price
item.id = UUID()
model.ticket.append(item)
}
}
struct View: View {
@StateObject controller = Controller()
var body: some View {
TicketView(controller: controller)
}
}
struct TicketView: View {
@State var controller: Controller
var body: some View {
List {
ForEach(controller.ticketItems, id:\Item.id) { (item: Item) in
Text(item.name!)
}
}
}
}
struct AnotherView: View {
@State var controller: Controller
Button {
controller.addItemToTicket(label: "", price: 0)
}
}