view 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
line wrap: on
line source

//
//  Favorites.swift
//  Simoleon
//
//  Created by Dennis Concepción Martín on 19/07/2021.
//

import SwiftUI

struct Favorites: View {
    @Environment(\.managedObjectContext) private var viewContext
    @FetchRequest(
        sortDescriptors: [NSSortDescriptor(keyPath: \Favorite.currencyPair, ascending: true)],
        animation: .default) private var favorite: FetchedResults<Favorite>
    
    var body: some View {
        VStack {
            if favorite.isEmpty {
                Group {
                    Text("Tap ") + Text(Image(systemName: "star"))
                    Text("to add a currency pair to favorites")
                        .padding(.top, 5)
                }
                .foregroundColor(Color(.systemGray))
            } else {
                List {
                    ForEach(favorite) { favorite in
                        NavigationLink(destination: Conversion(showNavigationView: false, currencyPair: favorite.currencyPair)) {
                            CurrencyRow(currencyPair: favorite.currencyPair)
                        }
                    }
                    .onDelete(perform: removeFromFavorites)
                }
                .listStyle(PlainListStyle())
            }
        }
        .navigationTitle("Favorites")
        .toolbar {
            #if os(iOS)
            EditButton()
            #endif
        }
        .if(UIDevice.current.userInterfaceIdiom == .phone) { content in
            NavigationView { content }
        }
    }
    
    private func removeFromFavorites(offsets: IndexSet) {
        withAnimation {
            offsets.map { favorite[$0] }.forEach(viewContext.delete)
            
            do {
                try viewContext.save()
            } catch {
                let nsError = error as NSError
                fatalError("Unresolved error \(nsError), \(nsError.userInfo)")
            }
        }
    }
}

struct Favorites_Previews: PreviewProvider {
    static var previews: some View {
        Favorites()
            .environment(\.managedObjectContext, PersistenceController.preview.container.viewContext)
    }
}