Mercurial > public > lazybear
comparison LazyBear/ContentView.swift @ 164:f74a364441ca
Start clean project
author | Dennis Concepción Martín <66180929+denniscm190@users.noreply.github.com> |
---|---|
date | Wed, 17 Feb 2021 20:27:04 +0100 |
parents | LazyBear/LazyBear/ContentView.swift@9d519f230f26 |
children | 125d268db489 |
comparison
equal
deleted
inserted
replaced
163:9d519f230f26 | 164:f74a364441ca |
---|---|
1 // | |
2 // ContentView.swift | |
3 // LazyBear | |
4 // | |
5 // Created by Dennis Concepción Martín on 17/2/21. | |
6 // | |
7 | |
8 import SwiftUI | |
9 import CoreData | |
10 | |
11 struct ContentView: View { | |
12 @Environment(\.managedObjectContext) private var viewContext | |
13 | |
14 @FetchRequest( | |
15 sortDescriptors: [NSSortDescriptor(keyPath: \Item.timestamp, ascending: true)], | |
16 animation: .default) | |
17 private var items: FetchedResults<Item> | |
18 | |
19 var body: some View { | |
20 List { | |
21 ForEach(items) { item in | |
22 Text("Item at \(item.timestamp!, formatter: itemFormatter)") | |
23 } | |
24 .onDelete(perform: deleteItems) | |
25 } | |
26 .toolbar { | |
27 #if os(iOS) | |
28 EditButton() | |
29 #endif | |
30 | |
31 Button(action: addItem) { | |
32 Label("Add Item", systemImage: "plus") | |
33 } | |
34 } | |
35 } | |
36 | |
37 private func addItem() { | |
38 withAnimation { | |
39 let newItem = Item(context: viewContext) | |
40 newItem.timestamp = Date() | |
41 | |
42 do { | |
43 try viewContext.save() | |
44 } catch { | |
45 // Replace this implementation with code to handle the error appropriately. | |
46 // 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. | |
47 let nsError = error as NSError | |
48 fatalError("Unresolved error \(nsError), \(nsError.userInfo)") | |
49 } | |
50 } | |
51 } | |
52 | |
53 private func deleteItems(offsets: IndexSet) { | |
54 withAnimation { | |
55 offsets.map { items[$0] }.forEach(viewContext.delete) | |
56 | |
57 do { | |
58 try viewContext.save() | |
59 } catch { | |
60 // Replace this implementation with code to handle the error appropriately. | |
61 // 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. | |
62 let nsError = error as NSError | |
63 fatalError("Unresolved error \(nsError), \(nsError.userInfo)") | |
64 } | |
65 } | |
66 } | |
67 } | |
68 | |
69 private let itemFormatter: DateFormatter = { | |
70 let formatter = DateFormatter() | |
71 formatter.dateStyle = .short | |
72 formatter.timeStyle = .medium | |
73 return formatter | |
74 }() | |
75 | |
76 struct ContentView_Previews: PreviewProvider { | |
77 static var previews: some View { | |
78 ContentView().environment(\.managedObjectContext, PersistenceController.preview.container.viewContext) | |
79 } | |
80 } |