Hi everyone I'm new to SwiftUI and i try to make a simple app for random choices,So when you create a list choices that will turn to a Spin-WheelView.For now, I face two problems: First. I don't know how save Angle and Array to UserDefaults; Second: I don't know to connect choices view to spin-wheel view. Any helps i will appreciate it! thank you all.
My model:
import SwiftUI
struct ChooseModel: Identifiable, Codable {
var id = UUID()
var decision: String
var choices: [String]
// i try to create Angle and [Colors] in my model,
// but they don't confirmed Codable, i don't know how to save them to User defaults.
// var startAngle: Angle
// var endAngle: Angle
// var colors: [Color]
}
Model View
import SwiftUI
class ChooseModelView: ObservableObject {
@Published var models = [ChooseModel]() {
didSet {
let encoder = JSONEncoder()
if let encoded = try? encoder.encode(models) {
UserDefaults.standard.set(encoded, forKey: "models")
}
}
}
init() {
if let items = UserDefaults.standard.data(forKey: "models") {
let decoder = JSONDecoder()
if let decoded = try? decoder.decode([ChooseModel].self, from: items) {
self.models = decoded
return
}
}
self.models = []
}
}
My View:
struct ChooseView: View {
@ObservedObject var chooseMV = ChooseModelView()
@State private var showingAddView = false
var body: some View {
NavigationView {
List {
ForEach(chooseMV.models) { item in
// Use NavigationLink to Each WheelView
HStack {
VStack(alignment: .leading) {
Text(item.decision)
.font(.title3)
HStack {
ForEach(item.choices, id: \.self) { choice in
Text("\(choice),")
.foregroundColor(Color.green)
}
}
}
Spacer()
}
}.onDelete(perform: remove)
}.navigationTitle("iChoose")
.navigationBarItems(leading: EditButton(), trailing: Button(action: {
self.showingAddView = true
}, label: {
Image(systemName: "plus")
}))
.sheet(isPresented: $showingAddView) {
AddView(chooseMV: self.chooseMV)
}
}
}
func remove(at offsets: IndexSet) {
chooseMV.models.remove(atOffsets: offsets)
}
}