0
    struct Test {
        
        @State private var steps = UserDefaults.standard.integer(forKey: "steps") {
            didSet {
                steps = UserDefaults.standard.integer(forKey: "steps")
            }
        }
        
        var body: some View {
            Stepper("Go up or down: \(steps)", value: $steps)
                .onChange(of: steps) { newValue in
                    UserDefaults.standard.set(newValue, forKey: "steps")
                }
        }
    }

Using didSet with a binding value doesn't call didSet method. Shouldn't it be called since the value is changing? So, I'm unable to save and show the saved value after this View is pushed back and forth from Navigation view. How should I solve this issue?

Aashish
  • 2,338
  • 2
  • 19
  • 24

1 Answers1

0

For brief explanation: Asperi's answer @ stackoverflow.com/a/62810288/12299030 )

Using @AppStorage instead of UserDefaults, it will automatically reinvoke your view’s body property when the value changes. That is, this wrapper effectively watches a key in UserDefaults, and will refresh your UI if that key changes. Perfect for Binding values.

struct Test {
    
    @AppStorage("steps") var steps = 0
    
    var body: some View {
        Stepper("Go up or down: \(steps)", value: $steps)
    }
}
Aashish
  • 2,338
  • 2
  • 19
  • 24