diff --git a/Gas Man/Vehicle/VehicleListView.swift b/Gas Man/Vehicle/VehicleListView.swift new file mode 100644 index 0000000..3814c8a --- /dev/null +++ b/Gas Man/Vehicle/VehicleListView.swift @@ -0,0 +1,59 @@ +// +// VehicleListView.swift +// Gas Man +// +// Created by Kameron Kenny on 3/18/25. +// + + +import SwiftUI +import CoreData + +struct VehicleListView: View { + @Environment(\.managedObjectContext) private var viewContext + @FetchRequest( + sortDescriptors: [NSSortDescriptor(keyPath: \Vehicle.make, ascending: true)], + animation: .default) + private var vehicles: FetchedResults + + @State private var showingAddVehicle = false + + var body: some View { + NavigationView { + List { + ForEach(vehicles) { vehicle in + NavigationLink(destination: VehicleDetailView(vehicle: vehicle)) { + VehicleRowView(vehicle: vehicle) + } + } + .onDelete(perform: deleteVehicles) + } + .navigationTitle("Vehicles") + .toolbar { + ToolbarItem(placement: .navigationBarTrailing) { + Button(action: { showingAddVehicle = true }) { + Label("Add Vehicle", systemImage: "plus") + } + } + ToolbarItem(placement: .navigationBarLeading) { + EditButton() + } + } + .sheet(isPresented: $showingAddVehicle) { + AddVehicleView().environment(\.managedObjectContext, viewContext) + } + } + } + + private func deleteVehicles(offsets: IndexSet) { + withAnimation { + offsets.map { vehicles[$0] }.forEach(viewContext.delete) + do { + try viewContext.save() + } catch { + let nsError = error as NSError + fatalError("Unresolved error \(nsError), \(nsError.userInfo)") + } + } + } +}