comparison Simoleon/FavoritesView.swift @ 187:13d5a8deb6c2

add AboutView and FavoritesView
author Dennis Concepcion Martin <dennisconcepcionmartin@gmail.com>
date Thu, 23 Dec 2021 16:12:22 +0100
parents
children
comparison
equal deleted inserted replaced
186:1ebd1c5dd302 187:13d5a8deb6c2
1 //
2 // FavoritesView.swift
3 // Simoleon
4 //
5 // Created by Dennis Concepción Martín on 23/12/21.
6 //
7
8 import SwiftUI
9 import CoreData
10
11 struct FavoritesView: View {
12 @Environment(\.managedObjectContext) private var viewContext
13 @FetchRequest(
14 sortDescriptors: [NSSortDescriptor(keyPath: \FavoritePair.baseCurrency, ascending: true)], animation: .default
15 ) private var favoritePairs: FetchedResults<FavoritePair>
16
17 var body: some View {
18 VStack {
19 if favoritePairs.isEmpty {
20 FavoritesPlaceholder()
21 } else {
22 List {
23 ForEach(favoritePairs, id:\.self) { favoritePair in
24 FavoriteRow(baseCurrency: favoritePair.baseCurrency!, quoteCurrency: favoritePair.quoteCurrency!)
25 }
26 .onDelete(perform: remove)
27 }
28 }
29 }
30 .toolbar {
31 #if os(iOS)
32 EditButton()
33 #endif
34 }
35 .navigationTitle("Favorites")
36 .if(UIDevice.current.userInterfaceIdiom == .phone) { content in
37 NavigationView { content }
38 }
39 }
40
41 // Remove favorite pair from favorites
42 private func remove(offsets: IndexSet) {
43 withAnimation {
44 offsets.map { favoritePairs[$0] }.forEach(viewContext.delete)
45
46 do {
47 try viewContext.save()
48 } catch {
49 let nsError = error as NSError
50 fatalError("Unresolved error \(nsError), \(nsError.userInfo)")
51 }
52 }
53 }
54 }
55
56 struct FavoritesView_Previews: PreviewProvider {
57 static var previews: some View {
58 FavoritesView()
59 }
60 }