123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899 |
- //
- // BudgetsListView.swift
- // ydnab
- //
- // Created by Andrea Franceschini on 23/09/2020.
- //
- import SwiftUI
- class BudgetsListViewModel: ObservableObject {
- @Published var items: BudgetsList
- init() {
- let applicationSupportURL = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask)[0]
- guard !applicationSupportURL.path.isEmpty else {
- print("Couldn't find Application Support path.")
- items = []
- return
- }
- let budgetsListURL = URL(fileURLWithPath: "Budgets.json", relativeTo: applicationSupportURL)
- guard FileManager.default.fileExists(atPath: budgetsListURL.path) else {
- print("Couldn't find the budgets list in Application Support.")
- print(budgetsListURL.path)
- items = []
- return
- }
- do {
- items = try JSONDecoder().decode(BudgetsList.self, from: Data.init(contentsOf: budgetsListURL))
- } catch {
- print("Couldn't open the budgets list.")
- print("Error: \(error)")
- items = []
- return
- }
- }
- }
- struct BudgetsListView: View {
- @State var currentBudgetId: UUID?
- @ObservedObject var budgetsList = BudgetsListViewModel()
- init(currentBudgetId: UUID?, budgetsList: BudgetsListViewModel = BudgetsListViewModel()) {
- self.currentBudgetId = currentBudgetId
- self.budgetsList = budgetsList
- }
- func createBudget() {
- print("Creating new budget...")
- print("... done creating new budget.")
- }
- var body: some View {
- VStack {
- List {
- ForEach(budgetsList.items) { budget in
- NavigationLink(destination: BudgetView(budget: budget, currentBudgetId: $currentBudgetId),
- tag: budget.id,
- selection: $currentBudgetId) {
- Text(budget.name)
- }
- }
- .onDelete(perform: { indexSet in
- print(indexSet)
- })
- .onMove(perform: { indices, newOffset in
- print("\(indices) :: \(newOffset)")
- })
- }
- Text(currentBudgetId?.uuidString ?? "--")
- }
- .listStyle(PlainListStyle())
- .navigationTitle("Budgets")
- .toolbar {
- #if os(iOS)
- ToolbarItem(placement: .primaryAction) {
- EditButton()
- }
- #endif
- ToolbarItem(placement: .navigationBarLeading) {
- Button("Add") {
- print(self)
- }
- }
- }
- }
- }
- struct BudgetsListView_Previews: PreviewProvider {
- static var previews: some View {
- NavigationView {
- BudgetsListView(currentBudgetId: UUID())
- }
- }
- }
|