无法将选择器结果保存到UserDefaults

时间:2020-10-04 22:39:05

标签: swiftui

我正在尝试将选择器的结果保存为用户默认值。用户默认的保存操作通过方法saveBase在类UserData中进行。

我已经通过按钮成功尝试了类似的技术,但是在选择器发出错误消息后,我的呼叫是

类型'()'不符合视图。

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 个答案:

答案 0 :(得分:1)

body中,您只能使用视图-您不能执行以下操作:

self.userData.saveBase(baseEntry: self.baseEntry)

您可以使用onChange保存值:

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中的保存/读取操作:

@AppStorage("base") var baseEntry = 0

并以与@State变量相同的方式在Picker中使用:

Picker(selection: $baseEntry, label: Text("Select Base >")) {