BudgetsListView.swift 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. //
  2. // BudgetsListView.swift
  3. // ydnab
  4. //
  5. // Created by Andrea Franceschini on 23/09/2020.
  6. //
  7. import SwiftUI
  8. class BudgetsListViewModel: ObservableObject {
  9. @Published var items: BudgetsList
  10. init() {
  11. let applicationSupportURL = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask)[0]
  12. guard !applicationSupportURL.path.isEmpty else {
  13. print("Couldn't find Application Support path.")
  14. items = []
  15. return
  16. }
  17. let budgetsListURL = URL(fileURLWithPath: "Budgets.json", relativeTo: applicationSupportURL)
  18. guard FileManager.default.fileExists(atPath: budgetsListURL.path) else {
  19. print("Couldn't find the budgets list in Application Support.")
  20. print(budgetsListURL.path)
  21. items = []
  22. return
  23. }
  24. do {
  25. items = try JSONDecoder().decode(BudgetsList.self, from: Data.init(contentsOf: budgetsListURL))
  26. } catch {
  27. print("Couldn't open the budgets list.")
  28. print("Error: \(error)")
  29. items = []
  30. return
  31. }
  32. }
  33. }
  34. struct BudgetsListView: View {
  35. @State var currentBudgetId: UUID?
  36. @ObservedObject var budgetsList = BudgetsListViewModel()
  37. init(currentBudgetId: UUID?, budgetsList: BudgetsListViewModel = BudgetsListViewModel()) {
  38. self.currentBudgetId = currentBudgetId
  39. self.budgetsList = budgetsList
  40. }
  41. func createBudget() {
  42. print("Creating new budget...")
  43. print("... done creating new budget.")
  44. }
  45. var body: some View {
  46. VStack {
  47. List {
  48. ForEach(budgetsList.items) { budget in
  49. NavigationLink(destination: BudgetView(budget: budget, currentBudgetId: $currentBudgetId),
  50. tag: budget.id,
  51. selection: $currentBudgetId) {
  52. Text(budget.name)
  53. }
  54. }
  55. .onDelete(perform: { indexSet in
  56. print(indexSet)
  57. })
  58. .onMove(perform: { indices, newOffset in
  59. print("\(indices) :: \(newOffset)")
  60. })
  61. }
  62. Text(currentBudgetId?.uuidString ?? "--")
  63. }
  64. .listStyle(PlainListStyle())
  65. .navigationTitle("Budgets")
  66. .toolbar {
  67. #if os(iOS)
  68. ToolbarItem(placement: .primaryAction) {
  69. EditButton()
  70. }
  71. #endif
  72. ToolbarItem(placement: .navigationBarLeading) {
  73. Button("Add") {
  74. print(self)
  75. }
  76. }
  77. }
  78. }
  79. }
  80. struct BudgetsListView_Previews: PreviewProvider {
  81. static var previews: some View {
  82. NavigationView {
  83. BudgetsListView(currentBudgetId: UUID())
  84. }
  85. }
  86. }