These are the three views in my to do list project.
I want to save data, so users' to do list will still be there after they launch the app.
But whenever I click on the icon "check.circle' or "circle", they cannot switch immediately. They will switch after I launch the app again.
I don't know how to let icon switched immediately.
Thanks in advance!!!
// Content View
import SwiftUI
struct ContentView: View {
@EnvironmentObject var listViewModel: ListViewModel
@State var newText: String = ""
@State var detents: PresentationDetent = .medium
@State var showSheet: Bool = false
static var item1 = ItemModel(title: "First", isCompleted: false)
var body: some View {
NavigationView {
List {
ForEach(listViewModel.items) { item in
ListRowView(item: item)
.onTapGesture {
listViewModel.updateItem(item: item). -> *
}
}
.onDelete(perform: listViewModel.delete)
.onMove(perform: listViewModel.moveItem)
}
.navigationTitle("To Do List")
.navigationBarItems(
leading: EditButton(),
trailing: Button(
action: {
showSheet.toggle()
}, label: {
Text("Add")
})
.sheet(
isPresented: $showSheet,
content: {
SecondScreen()
.presentationDetents([.height(500)])
}
))
}
}
}
// List View Model -> *
func saveItems() {
if let encodedData = try? JSONEncoder().encode(items) {
UserDefaults.standard.set(encodedData, forKey: itemsKey)
}
}
// Item Model
import Foundation
struct ItemModel: Identifiable, Codable {
let id: String
let title: String
var isCompleted: Bool
init(id: String = UUID().uuidString, title: String, isCompleted: Bool) {
self.id = id
self.title = title
self.isCompleted = isCompleted
}
func updateCompletion() -> ItemModel {. -> *
return ItemModel(id: id, title: title, isCompleted: !isCompleted)
}
}