Ei kuvausta

ContentView.swift 2.5KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  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. struct ContentView: View {
  10. @Environment(\.managedObjectContext) private var viewContext
  11. @FetchRequest(
  12. sortDescriptors: [NSSortDescriptor(keyPath: \Item.timestamp, ascending: true)],
  13. animation: .default)
  14. private var items: FetchedResults<Item>
  15. var body: some View {
  16. List {
  17. ForEach(items) { item in
  18. Text("Item at \(item.timestamp!, formatter: itemFormatter)")
  19. }
  20. .onDelete(perform: deleteItems)
  21. }
  22. .toolbar {
  23. #if os(iOS)
  24. EditButton()
  25. #endif
  26. Button(action: addItem) {
  27. Label("Add Item", systemImage: "plus")
  28. }
  29. }
  30. }
  31. private func addItem() {
  32. withAnimation {
  33. let newItem = Item(context: viewContext)
  34. newItem.timestamp = Date()
  35. do {
  36. try viewContext.save()
  37. } catch {
  38. // Replace this implementation with code to handle the error appropriately.
  39. // 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.
  40. let nsError = error as NSError
  41. fatalError("Unresolved error \(nsError), \(nsError.userInfo)")
  42. }
  43. }
  44. }
  45. private func deleteItems(offsets: IndexSet) {
  46. withAnimation {
  47. offsets.map { items[$0] }.forEach(viewContext.delete)
  48. do {
  49. try viewContext.save()
  50. } catch {
  51. // Replace this implementation with code to handle the error appropriately.
  52. // 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.
  53. let nsError = error as NSError
  54. fatalError("Unresolved error \(nsError), \(nsError.userInfo)")
  55. }
  56. }
  57. }
  58. }
  59. private let itemFormatter: DateFormatter = {
  60. let formatter = DateFormatter()
  61. formatter.dateStyle = .short
  62. formatter.timeStyle = .medium
  63. return formatter
  64. }()
  65. struct ContentView_Previews: PreviewProvider {
  66. static var previews: some View {
  67. ContentView().environment(\.managedObjectContext, PersistenceController.preview.container.viewContext)
  68. }
  69. }