changeset 267:e8223540f3f3

Add fav symbol on CompanyView
author Dennis Concepción Martín <66180929+denniscm190@users.noreply.github.com>
date Sun, 14 Mar 2021 13:24:25 +0100
parents cc260d53fcf8
children 083ca8dc3499
files LazyBear/UI/CompanyView.swift
diffstat 1 files changed, 21 insertions(+), 6 deletions(-) [+]
line wrap: on
line diff
--- a/LazyBear/UI/CompanyView.swift	Sun Mar 14 13:24:01 2021 +0100
+++ b/LazyBear/UI/CompanyView.swift	Sun Mar 14 13:24:25 2021 +0100
@@ -17,8 +17,7 @@
     @EnvironmentObject var hudManager: HudManager
     @EnvironmentObject var companyOption: CompanyOption
     @Environment(\.managedObjectContext) private var moc
-    @FetchRequest(entity: Company.entity(), sortDescriptors: [])
-    var companies: FetchedResults<Company>
+    @FetchRequest(entity: Company.entity(), sortDescriptors: []) var companies: FetchedResults<Company>
     
     var body: some View {
         GeometryReader { geo in
@@ -52,9 +51,12 @@
             ToolbarItem(placement: .navigationBarTrailing) {
                 let symbols = companies.map { $0.symbol }
                 if !symbols.contains(symbol) {
-                    Button(action: { add() }) {
+                    Button(action: { addCompany() }) {
                         Image(systemName: "star")
-                            .imageScale(.large)
+                    }
+                } else {
+                    Button(action: { removeCompany() }) {
+                        Image(systemName: "star.fill")
                     }
                 }
             }
@@ -62,7 +64,7 @@
     }
     
     // Add to watchlist
-    private func add() {
+    private func addCompany() {
         let generator = UINotificationFeedbackGenerator()  // Haptic
         let company = Company(context: moc)
         company.symbol = symbol
@@ -71,11 +73,24 @@
             try moc.save()
             hudManager.selectHud(type: .notification)
             generator.notificationOccurred(.success)
-            print("Company saved.")
+            print("Company saved")
         } catch {
             print(error.localizedDescription)
         }
     }
+    
+    private func removeCompany() {
+        let symbols = companies.map { $0.symbol }
+        let index = symbols.firstIndex(of: symbol)
+        let company = companies[index!]
+        moc.delete(company)
+        do {
+            try moc.save()
+            print("Company deleted")
+        } catch {
+            // Error
+        }
+    }
 }
 
 struct CompanyView_Previews: PreviewProvider {