Unable to Save Picker Result to UserDefaults

前端 未结 1 533
自闭症患者
自闭症患者 2021-01-26 05: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 tec

1条回答
  •  无人及你
    2021-01-26 06:45

    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 >")) {
    

    0 讨论(0)
提交回复
热议问题