-
Notifications
You must be signed in to change notification settings - Fork 3
/
ContentView.swift
67 lines (59 loc) · 2.09 KB
/
ContentView.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
//
// ContentView.swift
// P11C Bookworm
//
// Created by Julian Moorhouse on 01/04/2021.
//
import CoreData
import SwiftUI
struct ContentView: View {
@Environment(\.managedObjectContext) var moc
@FetchRequest(entity: Book.entity(), sortDescriptors: [
NSSortDescriptor(keyPath: \Book.title, ascending: true),
NSSortDescriptor(keyPath: \Book.author, ascending: true)
]) var books: FetchedResults<Book>
@State private var showingAddScreen = false
var body: some View {
NavigationView {
List {
ForEach(books, id: \.self) { book in
NavigationLink(destination: DetailView(book: book)) {
EmojiRatingView(rating: book.rating)
.font(.largeTitle)
VStack(alignment: .leading) {
Text(book.title ?? "Unknown title")
.font(.headline)
.foregroundColor(book.rating == 1 ? .red : .primary)
Text(book.author ?? "Unknown author")
.foregroundColor(.secondary)
}
}
}
.onDelete(perform: deleteBooks)
}
.navigationBarTitle("Bookworm")
.navigationBarItems(leading: EditButton(), trailing:
Button(action: {
self.showingAddScreen.toggle()
}) {
Image(systemName: "plus")
}
)
.sheet(isPresented: $showingAddScreen) {
AddBookView().environment(\.managedObjectContext, self.moc)
}
}
}
func deleteBooks(at offsets: IndexSet) {
for offset in offsets {
let book = books[offset]
moc.delete(book)
}
try? moc.save()
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView().environment(\.managedObjectContext, PersistenceController.preview.container.viewContext)
}
}