无法将选取器结果保存到 UserDefaults [英] Unable to Save Picker Result to UserDefaults
问题描述
我正在尝试将选择器的结果保存为用户默认值.用户默认保存操作发生在类 UserData 中,通过方法 saveBase.
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")
}
}
推荐答案
在 body
中,您只能使用视图 - 您不能执行以下操作:
In the body
you can only use Views - you can't perform operations like:
self.userData.saveBase(baseEntry: self.baseEntry)
您可以使用 onChange
来保存值:
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)
}
}
请注意,您还可以使用 @AppStorage
从 UserDefaults 自动保存/读取:
Note that you can also use @AppStorage
to automate saving/reading from UserDefaults:
@AppStorage("base") var baseEntry = 0
并以与 @State
变量相同的方式在 Picker 中使用:
and use in the Picker in the same way as a @State
variable:
Picker(selection: $baseEntry, label: Text("Select Base >")) {
这篇关于无法将选取器结果保存到 UserDefaults的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!