Home > Net >  SwiftUI: reading data from ObservableObject
SwiftUI: reading data from ObservableObject

Time:04-12

I am new to SwiftUI and created a Todo model. I then have a class that represents the container so that I can have an array of Todos and methods on it later on. I made TodoContainer an ObservableObject and then observing it after instantiating it: @ObservedObject var items = TodoContainer().
I am iterating through the list and expecting anytime I click the button, shouldn't it appear in the list since it's creating a new Todo each time and allTodos should have the array of all Todos?

import SwiftUI

struct Todo: Identifiable {
    var id = UUID()
    var name: String;
    var priority: Int;
}

class TodoContainer: ObservableObject {
    @Published var allTodos = [Todo]();
}



struct ContentView: View {
    @ObservedObject var items = TodoContainer()
    
    var body: some View {
        Button("Create New") {
            Todo(name: "New one", priority: Int.random(in: 1..<100))
        }
        List(items.allTodos, id: \.id){item in
            Text(item.name)
        }
    }
}

CodePudding user response:

You need to add the created todo to the view model's allTodos. Xcode may have shown you an error about an unused expression previously.

import SwiftUI

struct Todo: Identifiable {
    var id = UUID()
    var name: String;
    var priority: Int;
}

class TodoContainer: ObservableObject {
    @Published var allTodos = [Todo]();
}

struct ContentView: View {
    @ObservedObject var items = TodoContainer()
    
    var body: some View {
        Button("Create New") {
            let todo = Todo(name: "New one", priority: Int.random(in: 1..<100))
            items.allTodos.append(todo) // here
        }
        List(items.allTodos, id: \.id){item in
            Text(item.name)
        }
    }
}
  • Related