add minimal generalized main/detail view
This commit is contained in:
@@ -0,0 +1,100 @@
|
||||
//
|
||||
// ContentView.swift
|
||||
// WorkoutsPlus
|
||||
//
|
||||
// Created by Felix Förtsch on 10.08.24.
|
||||
//
|
||||
|
||||
import SwiftUI
|
||||
import SwiftData
|
||||
|
||||
struct ItemLibrary: View {
|
||||
@Environment(\.modelContext) private var modelContext
|
||||
@Query private var items: [Item]
|
||||
|
||||
@State private var isPresentingNewItemSheet = false
|
||||
|
||||
let initialDataSet = [
|
||||
"Pull-up",
|
||||
"Push-up",
|
||||
"Dips",
|
||||
"Rows",
|
||||
"Split Squat"
|
||||
]
|
||||
|
||||
var body: some View {
|
||||
NavigationView {
|
||||
List {
|
||||
ForEach(items) { item in
|
||||
NavigationLink(destination: ItemDetailsView(item: item)) {
|
||||
Text(item.name)
|
||||
}
|
||||
}
|
||||
.onDelete(perform: deleteItem)
|
||||
}
|
||||
.onAppear {
|
||||
if items.isEmpty {
|
||||
loadInitialData(exercises: initialDataSet)
|
||||
}
|
||||
}
|
||||
.toolbar {
|
||||
ToolbarItem(placement: .navigationBarTrailing) {
|
||||
Button {
|
||||
createNewItem()
|
||||
} label: {
|
||||
Label("Add Exercise", systemImage: "plus")
|
||||
}
|
||||
}
|
||||
}
|
||||
.sheet(isPresented: $isPresentingNewItemSheet) {
|
||||
let newItem = Item(name: "")
|
||||
NavigationView {
|
||||
ItemDetailsView(item: newItem, isPresentedAsSheet: true)
|
||||
.onDisappear {
|
||||
if !newItem.name.isEmpty {
|
||||
saveItem(item: newItem)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private func createNewItem() {
|
||||
isPresentingNewItemSheet = true
|
||||
}
|
||||
|
||||
private func saveItem(item: Item) {
|
||||
modelContext.insert(item)
|
||||
try? modelContext.save()
|
||||
}
|
||||
|
||||
private func deleteItem(offsets: IndexSet) {
|
||||
withAnimation {
|
||||
for index in offsets {
|
||||
modelContext.delete(items[index])
|
||||
}
|
||||
try? modelContext.save()
|
||||
}
|
||||
}
|
||||
|
||||
private func loadInitialData(exercises: [String]) {
|
||||
var items: [Item] = []
|
||||
|
||||
for exercise in exercises {
|
||||
let item = Item(name: exercise)
|
||||
items.append(item)
|
||||
}
|
||||
|
||||
for item in items {
|
||||
modelContext.insert(item)
|
||||
}
|
||||
|
||||
try? modelContext.save()
|
||||
}
|
||||
}
|
||||
|
||||
#Preview {
|
||||
ItemLibrary()
|
||||
.modelContainer(for: Item.self, inMemory: true)
|
||||
}
|
||||
Reference in New Issue
Block a user