Here's
Info.swift and
CardsView:
Info.swift:Code Block // |
// Info.swift |
// Lunch Card (iOS) |
// |
// Created by Joshua Srery on 12/21/20. |
// Additional code by OOPer on Apple Developer Forums |
// |
|
import Foundation |
|
struct CardInfo: Identifiable, Codable { |
var name: String = "" |
var id: String = "" |
var cname: String = "" |
// var code: String = "" |
} |
|
class CardsInfo: ObservableObject { |
@Published var newCard: CardInfo = CardInfo() |
@Published var cards: [CardInfo] = [] |
|
func add() { |
cards.append(newCard) |
} |
} |
|
extension CardsInfo { |
var dataUrl: URL { |
FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0] |
.appendingPathComponent("cards.json") |
} |
|
func saveCards() { |
do { |
let data = try JSONEncoder().encode(cards) |
try data.write(to: dataUrl, options: .atomic) |
} catch { |
print(error) |
} |
} |
|
func loadCards() { |
do { |
if FileManager.default.fileExists(atPath: dataUrl.path) { |
return |
} |
let data = try Data(contentsOf: dataUrl) |
let cards = try JSONDecoder().decode([CardInfo].self, from: data) |
self.cards = cards |
} catch { |
print(error) |
} |
} |
} |
|
class SheetInfo: ObservableObject { |
@Published var showSheetView = false |
} |
CardsView:Code Block // |
// CardsView.swift |
// Lunch Card (iOS) |
// |
// Created by Joshua Srery on 12/17/20. |
// Additional code by OOPer on Apple Developer Forums |
// |
|
import SwiftUI |
|
struct Card: Identifiable { |
let id = UUID() |
let title: String |
} |
|
struct CardsView: View { |
@StateObject var cardsInfo = CardsInfo() |
@StateObject var sheetInfo = SheetInfo() |
@State private var editMode = EditMode.inactive |
@State var presentMode = false |
|
var body: some View { |
NavigationView { |
List { |
ForEach(cardsInfo.cards) { card in |
NavigationLink(destination: CardFullView(cname: card.cname, name: card.name, id: card.id)) { |
CardRow(cname: card.cname, name: card.name, id: card.id) |
|
} |
} |
.onDelete(perform: onDelete) |
.onMove(perform: onMove) |
}.listStyle(PlainListStyle()) |
.navigationTitle("Cards") |
.toolbar { |
ToolbarItem(placement: .navigationBarLeading) { |
EditButton() |
} |
ToolbarItem(placement: .navigationBarTrailing) { |
Button(action: { |
self.sheetInfo.showSheetView.toggle() |
}) { |
Image(systemName: "plus") |
} |
} |
} |
.environment(\.editMode, $editMode) |
.sheet(isPresented: $sheetInfo.showSheetView) { |
AddView(cardsInfo: cardsInfo, sheetInfo: sheetInfo) |
} |
.onAppear { |
cardsInfo.loadCards() // <- Preferred Placement |
} |
} |
} |
|
private func onDelete(offsets: IndexSet) { |
self.presentMode.toggle() |
cardsInfo.cards.remove(atOffsets: offsets) |
cardsInfo.saveCards() |
} |
|
private func onMove(source: IndexSet, destination: Int) { |
cardsInfo.cards.move(fromOffsets: source, toOffset: destination) |
cardsInfo.saveCards() |
} |
} |
Please tell me if you need more.