comparison Simoleon/Helpers/FavouriteButton.swift @ 21:c3dda63f50ed v1.1

Added Core Data and UI changes - Implement Watchlist - Change conversion design - Improve UX
author Dennis Concepción Martín <dennisconcepcionmartin@gmail.com>
date Mon, 19 Jul 2021 19:27:12 +0100
parents
children 3596690dda73
comparison
equal deleted inserted replaced
20:f8aabe5b7251 21:c3dda63f50ed
1 //
2 // FavouriteButton.swift
3 // Simoleon
4 //
5 // Created by Dennis Concepción Martín on 19/07/2021.
6 //
7
8 import SwiftUI
9
10 struct FavouriteButton: View {
11 var currencyPair: String
12 @Environment(\.managedObjectContext) private var viewContext
13 @FetchRequest(sortDescriptors: []) private var favourite: FetchedResults<Favourite>
14
15 var body: some View {
16 Button(action: {
17 if isFavourite() {
18 removeFromFavourites()
19 } else {
20 addToFavourites()
21 }
22 }) {
23 RoundedRectangle(cornerRadius: 25)
24 .foregroundColor(Color(.secondarySystemBackground))
25 .frame(width: 75, height: 75)
26 .overlay(
27 Image(systemName: generateStar())
28 .font(.system(size: 28))
29 .foregroundColor(Color(.systemYellow))
30
31 )
32 }
33 }
34
35 private func isFavourite() -> Bool {
36 let favouriteCurrencyPairs = favourite.map { $0.currencyPair }
37
38 if favouriteCurrencyPairs.contains(currencyPair) {
39 return true
40 } else {
41 return false
42 }
43 }
44
45 private func generateStar() -> String {
46 if isFavourite() {
47 return "star.fill"
48 } else {
49 return "star"
50 }
51 }
52
53 private func removeFromFavourites() {
54 withAnimation {
55 let favouriteObject = favourite.first(where: { $0.currencyPair == currencyPair })
56 viewContext.delete(favouriteObject ?? Favourite())
57
58 do {
59 try viewContext.save()
60 } catch {
61 let nsError = error as NSError
62 fatalError("Unresolved error \(nsError), \(nsError.userInfo)")
63 }
64 }
65 }
66
67 private func addToFavourites() {
68 withAnimation {
69 let favourite = Favourite(context: viewContext)
70 favourite.currencyPair = currencyPair
71
72 do {
73 try viewContext.save()
74 } catch {
75 let nsError = error as NSError
76 fatalError("Unresolved error \(nsError), \(nsError.userInfo)")
77 }
78 }
79 }
80 }
81
82 struct FavouriteButton_Previews: PreviewProvider {
83 static var previews: some View {
84 FavouriteButton(currencyPair: "USD/GBP")
85 }
86 }