comparison Simoleon/Favorites.swift @ 53:b0bce2c8e4a9

Refactor UK spelling to US
author Dennis Concepción Martín <dennisconcepcionmartin@gmail.com>
date Tue, 27 Jul 2021 09:44:51 +0100
parents Simoleon/Favourites.swift@75c1a05176f6
children b6f8661300f2
comparison
equal deleted inserted replaced
52:3fa127885e60 53:b0bce2c8e4a9
1 //
2 // Favorites.swift
3 // Simoleon
4 //
5 // Created by Dennis Concepción Martín on 19/07/2021.
6 //
7
8 import SwiftUI
9
10 struct Favorites: View {
11 @Environment(\.managedObjectContext) private var viewContext
12 @FetchRequest(
13 sortDescriptors: [NSSortDescriptor(keyPath: \Favorite.currencyPair, ascending: true)],
14 animation: .default) private var favorite: FetchedResults<Favorite>
15
16 var body: some View {
17 VStack {
18 if favorite.isEmpty {
19 Group {
20 Text("Tap ") + Text(Image(systemName: "star"))
21 Text("to add a currency pair to favorites")
22 .padding(.top, 5)
23 }
24 .foregroundColor(Color(.systemGray))
25 } else {
26 List {
27 ForEach(favorite) { favorite in
28 NavigationLink(destination: Conversion(showNavigationView: false, currencyPair: favorite.currencyPair)) {
29 CurrencyRow(currencyPair: favorite.currencyPair)
30 }
31 }
32 .onDelete(perform: removeFromFavorites)
33 }
34 .listStyle(PlainListStyle())
35 }
36 }
37 .navigationTitle("Favorites")
38 .toolbar {
39 #if os(iOS)
40 EditButton()
41 #endif
42 }
43 .if(UIDevice.current.userInterfaceIdiom == .phone) { content in
44 NavigationView { content }
45 }
46 }
47
48 private func removeFromFavorites(offsets: IndexSet) {
49 withAnimation {
50 offsets.map { favorite[$0] }.forEach(viewContext.delete)
51
52 do {
53 try viewContext.save()
54 } catch {
55 let nsError = error as NSError
56 fatalError("Unresolved error \(nsError), \(nsError.userInfo)")
57 }
58 }
59 }
60 }
61
62 struct Favorites_Previews: PreviewProvider {
63 static var previews: some View {
64 Favorites()
65 .environment(\.managedObjectContext, PersistenceController.preview.container.viewContext)
66 }
67 }