ContentView.swift 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. //
  2. // ContentView.swift
  3. // ydnab
  4. //
  5. // Created by Andrea Franceschini on 20/09/2020.
  6. //
  7. import SwiftUI
  8. import CoreData
  9. struct ContentView: View {
  10. @State var budgetSections: [BudgetSection] = []
  11. @State var currenBudgetName = ""
  12. @Environment(\.managedObjectContext) private var viewContext
  13. @FetchRequest(
  14. sortDescriptors: [NSSortDescriptor(keyPath: \Item.timestamp, ascending: true)],
  15. animation: .default)
  16. private var items: FetchedResults<Item>
  17. var body: some View {
  18. List {
  19. ForEach(budgetSections, id: \.id) { section in
  20. Text(section.name)
  21. }
  22. .onDelete(perform: deleteItems)
  23. }
  24. .navigationTitle(currenBudgetName)
  25. }
  26. private func addItem() {
  27. withAnimation {
  28. let newItem = Item(context: viewContext)
  29. newItem.timestamp = Date()
  30. do {
  31. try viewContext.save()
  32. } catch {
  33. // Replace this implementation with code to handle the error appropriately.
  34. // 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.
  35. let nsError = error as NSError
  36. fatalError("Unresolved error \(nsError), \(nsError.userInfo)")
  37. }
  38. }
  39. }
  40. private func deleteItems(offsets: IndexSet) {
  41. withAnimation {
  42. offsets.map { items[$0] }.forEach(viewContext.delete)
  43. do {
  44. try viewContext.save()
  45. } catch {
  46. // Replace this implementation with code to handle the error appropriately.
  47. // 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.
  48. let nsError = error as NSError
  49. fatalError("Unresolved error \(nsError), \(nsError.userInfo)")
  50. }
  51. }
  52. }
  53. }
  54. private let itemFormatter: DateFormatter = {
  55. let formatter = DateFormatter()
  56. formatter.dateStyle = .short
  57. formatter.timeStyle = .medium
  58. return formatter
  59. }()
  60. struct ContentView_Previews: PreviewProvider {
  61. static var previews: some View {
  62. ContentView()
  63. .environment(\.managedObjectContext, PersistenceController.preview.container.viewContext)
  64. }
  65. }