问题
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 technique successfully with a button but my call after the picker gives the famous error:
Type '()' cannot conform to view.
struct aboutView: View {
@EnvironmentObject var userData: UserData
@State private var baseEntry: Int = 0
let base = ["Level 1", "Level 2","Level 3","Level 4"]
var body: some View {
Text("comment")
Text("comment")
Text("comment")
Section {
Picker(selection: $baseEntry, label: Text("Select Base >")) {
ForEach(0 ..< self.base.count) {
Text(self.base[$0]).tag($0)
}
self.userData.saveBase(baseEntry: self.baseEntry)
}
}
.padding()
}
}
class UserData: ObservableObject {
@Published var baseCurr: Int
func saveBase(baseEntry: Int) -> () {
baseCurr = baseEntry
let defaults = UserDefaults.standard
defaults.set(self.baseCurr, forKey: "base")
}
}
回答1:
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 >")) {
来源:https://stackoverflow.com/questions/64200555/unable-to-save-picker-result-to-userdefaults