No Description

ContentView.swift 2.7KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. //
  2. // ContentView.swift
  3. // Comedores Sociales
  4. //
  5. // Created by Hector Carrion on 10/24/20.
  6. //
  7. import SwiftUI
  8. import CoreData
  9. let lightGreyColor = Color(red: 239.0/255.0, green: 243.0/255.0, blue: 244.0/255.0, opacity: 1.0)
  10. let darkGreyColor = Color(red: 41.0/255.0, green: 42.0/255.0, blue: 47.0/255.0, opacity: 1.0)
  11. struct ContentView: View {
  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(items) { item in
  20. Text("Item at \(item.timestamp!, formatter: itemFormatter)")
  21. }
  22. .onDelete(perform: deleteItems)
  23. }
  24. .toolbar {
  25. #if os(iOS)
  26. EditButton()
  27. #endif
  28. Button(action: addItem) {
  29. Label("Add Item", systemImage: "plus")
  30. }
  31. }
  32. }
  33. private func addItem() {
  34. withAnimation {
  35. let newItem = Item(context: viewContext)
  36. newItem.timestamp = Date()
  37. do {
  38. try viewContext.save()
  39. } catch {
  40. // Replace this implementation with code to handle the error appropriately.
  41. // 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.
  42. let nsError = error as NSError
  43. fatalError("Unresolved error \(nsError), \(nsError.userInfo)")
  44. }
  45. }
  46. }
  47. private func deleteItems(offsets: IndexSet) {
  48. withAnimation {
  49. offsets.map { items[$0] }.forEach(viewContext.delete)
  50. do {
  51. try viewContext.save()
  52. } catch {
  53. // Replace this implementation with code to handle the error appropriately.
  54. // 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.
  55. let nsError = error as NSError
  56. fatalError("Unresolved error \(nsError), \(nsError.userInfo)")
  57. }
  58. }
  59. }
  60. }
  61. private let itemFormatter: DateFormatter = {
  62. let formatter = DateFormatter()
  63. formatter.dateStyle = .short
  64. formatter.timeStyle = .medium
  65. return formatter
  66. }()
  67. struct ContentView_Previews: PreviewProvider {
  68. static var previews: some View {
  69. ContentView().environment(\.managedObjectContext, PersistenceController.preview.container.viewContext)
  70. }
  71. }