comparison LazyBear/Views/Search/Helpers/SearchedCompanyItem.swift @ 389:db8bc3ed526a

Implementing add to watchlist feature from SearchView
author Dennis Concepción Martín <66180929+denniscm190@users.noreply.github.com>
date Sun, 25 Apr 2021 16:42:26 +0200
parents 280cbc5653b5
children 8ec37b2baafd
comparison
equal deleted inserted replaced
388:79c39987aaa4 389:db8bc3ed526a
8 import SwiftUI 8 import SwiftUI
9 9
10 struct SearchedCompanyItem: View { 10 struct SearchedCompanyItem: View {
11 var company: SearchResponse 11 var company: SearchResponse
12 12
13 @Environment(\.managedObjectContext) private var moc
14 @FetchRequest(entity: WatchlistCompany.entity(), sortDescriptors: [])
15 var watchlistCompany: FetchedResults<WatchlistCompany>
16
17 @State private var showingActionSheet = false
18
13 var body: some View { 19 var body: some View {
20 let watchlistSymbols = watchlistCompany.map { $0.symbol }
14 HStack { 21 HStack {
22 Button(action: { self.showingActionSheet = true }) {
23 if watchlistSymbols.contains(company.symbol!) {
24 Image(systemName: "star.fill")
25 .foregroundColor(.yellow)
26 .imageScale(.large)
27 } else {
28 Image(systemName: "star")
29 .foregroundColor(.yellow)
30 .imageScale(.large)
31 }
32 }
33 .buttonStyle(PlainButtonStyle())
34
15 VStack(alignment: .leading) { 35 VStack(alignment: .leading) {
16 Text(company.symbol!.uppercased()) 36 Text(company.symbol!.uppercased())
17 .fontWeight(.semibold) 37 .fontWeight(.semibold)
18 38
19 Text(company.securityName!.capitalized) 39 Text(company.securityName!.capitalized)
27 .fontWeight(.semibold) 47 .fontWeight(.semibold)
28 48
29 Text(company.region!) 49 Text(company.region!)
30 } 50 }
31 } 51 }
52 .actionSheet(isPresented: $showingActionSheet) {
53 ActionSheet(title: Text("Your watchlists"), message: Text("Select"), buttons: generateButtons())
54 }
55 }
56
57 // Get watchlist names -> generate buttons
58 private func generateButtons() -> [ActionSheet.Button] {
59 var actionButtons = [ActionSheet.Button]()
60 let watchlists = Set(watchlistCompany.map { $0.watchlist })
61
62 for watchlistName in watchlists {
63 actionButtons.append(
64 .default(Text(watchlistName)) {
65 addCompany(company.symbol!, company.securityName!, watchlistName)
66 }
67 )
68 }
69
70 actionButtons.append(.cancel())
71
72 return actionButtons
73 }
74
75 // Add to watchlist
76 private func addCompany(_ symbol: String, _ name: String, _ watchlist: String) {
77 let watchlistCompany = WatchlistCompany(context: moc)
78 watchlistCompany.symbol = symbol
79 watchlistCompany.name = name
80 watchlistCompany.watchlist = watchlist
81 do {
82 try moc.save()
83 print("Company saved")
84 } catch {
85 print(error.localizedDescription)
86 }
32 } 87 }
33 } 88 }
34 89
35 struct CompanyRow_Previews: PreviewProvider { 90 struct CompanyRow_Previews: PreviewProvider {
36 static var previews: some View { 91 static var previews: some View {