1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677 |
- //
- // ContentView.swift
- // ydnab
- //
- // Created by Andrea Franceschini on 20/09/2020.
- //
- import SwiftUI
- import CoreData
- struct ContentView: View {
- @State var budgetSections: [BudgetSection] = []
- @State var currenBudgetName = ""
- @Environment(\.managedObjectContext) private var viewContext
- @FetchRequest(
- sortDescriptors: [NSSortDescriptor(keyPath: \Item.timestamp, ascending: true)],
- animation: .default)
- private var items: FetchedResults<Item>
- var body: some View {
- List {
- ForEach(budgetSections, id: \.id) { section in
- Text(section.name)
- }
- .onDelete(perform: deleteItems)
- }
- .navigationTitle(currenBudgetName)
- }
- private func addItem() {
- withAnimation {
- let newItem = Item(context: viewContext)
- newItem.timestamp = Date()
- do {
- try viewContext.save()
- } catch {
- // Replace this implementation with code to handle the error appropriately.
- // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
- let nsError = error as NSError
- fatalError("Unresolved error \(nsError), \(nsError.userInfo)")
- }
- }
- }
- private func deleteItems(offsets: IndexSet) {
- withAnimation {
- offsets.map { items[$0] }.forEach(viewContext.delete)
- do {
- try viewContext.save()
- } catch {
- // Replace this implementation with code to handle the error appropriately.
- // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
- let nsError = error as NSError
- fatalError("Unresolved error \(nsError), \(nsError.userInfo)")
- }
- }
- }
- }
- private let itemFormatter: DateFormatter = {
- let formatter = DateFormatter()
- formatter.dateStyle = .short
- formatter.timeStyle = .medium
- return formatter
- }()
- struct ContentView_Previews: PreviewProvider {
- static var previews: some View {
- ContentView()
- .environment(\.managedObjectContext, PersistenceController.preview.container.viewContext)
- }
- }
|