Another way of doing it.
import SwiftUI
import Combine
struct ContentView: View {
@ObservedObject var api = TodoAPI()
var body: some View {
VStack {
List{
Button(action: {
api.fetchTodos()
}, label: {
Text("Get todos")
})
ForEach(0..<api.todos.count) { idx in
HStack {
Image(systemName: (api.todos[idx].isDone ? "checkmark.circle.fill" : "checkmark.circle"))
ToDoRowView(todo: $api.todos[idx])
}
}
}
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
struct ToDoRowView: View {
@Binding var todo:Todo
var body: some View {
HStack {
Text(todo.title)
.font(.title3)
.padding()
Spacer()
Button(action: {
self.todo.isDone.toggle()
}, label: {
Text("DONE").padding(5).background(Color( colorLiteral(red: 0.721568644, green: 0.8862745166, blue: 0.5921568871, alpha: 1)))
})
}
}
}
struct Todo: Identifiable {
var id = UUID()
var title: String
var isDone = false
}
class TodoAPI: ObservableObject {
@Published var todos:[Todo] = []
init() {
fetchTodos()
}
//fetch data from API
func fetchTodos(){
todos = [
Todo(title: "Feed the dog"),
Todo(title: "Drink 5 glass of water"),
Todo(title: "Do the homework"),
Todo(title: "Call grandma"),
Todo(title: "Task - \(Int.random(in: 1...100))")
]
}
}