Unable to Save Picker Result to UserDefaults

折月煮酒 提交于 2020-11-29 21:19:59

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!