I am trying to save the result of a picker to user defaults. The user default save operation occurs in the class UserData via method saveBase.
I have tried a similar tec
In the body
you can only use Views - you can't perform operations like:
self.userData.saveBase(baseEntry: self.baseEntry)
You may use onChange
to save the value:
Picker(selection: $baseEntry, label: Text("Select Base >")) {
ForEach(0 ..< self.base.count) {
Text(self.base[$0]).tag($0)
}
.onChange(of: baseEntry) {
self.userData.saveBase(baseEntry: $0)
}
}
Note that you can also use @AppStorage
to automate saving/reading from UserDefaults:
@AppStorage("base") var baseEntry = 0
and use in the Picker in the same way as a @State
variable:
Picker(selection: $baseEntry, label: Text("Select Base >")) {