2
votes

I'm new in SwiftUI and want to save the user choice from picker. I know I need UserDefaults for that, but I don't know how to use UserDefaults in this case.

struct ContentView: View {

    @Environment(\.colorScheme) var colorScheme
    @State var PickerSelection = 0
    
    //PickerStyle

    init() {
        UISegmentedControl.appearance().selectedSegmentTintColor = .init(UIColor(named: "Color_Picker")!)
        UISegmentedControl.appearance().setTitleTextAttributes([.foregroundColor: UIColor.white], for: .selected)
        UISegmentedControl.appearance().setTitleTextAttributes([.foregroundColor: UIColor.init(named: "Color_Picker")!], for: .normal)
    }
    
    var body: some View {
        VStack {
            Picker("", selection: $PickerSelection) {
            Text("Selection 1").tag(0)
            Text("Selection 2").tag(1)
            } .pickerStyle(SegmentedPickerStyle()).padding(.horizontal, 100)
            Text("Hello World!")
    }
}
1

1 Answers

2
votes

You can use .onReceive with help of Just publisher (to be compatible with iOS 13*)

import Combine
struct ContentView: View {

    @Environment(\.colorScheme) var colorScheme
    @State var PickerSelection = UserDefaults.standard.integer(forKey: "Picker")

    //PickerStyle

    init() {
        UISegmentedControl.appearance().selectedSegmentTintColor = .init(UIColor(named: "Color_Picker")!)
        UISegmentedControl.appearance().setTitleTextAttributes([.foregroundColor: UIColor.white], for: .selected)
        UISegmentedControl.appearance().setTitleTextAttributes([.foregroundColor: UIColor.init(named: "Color_Picker")!], for: .normal)
    }

    var body: some View {
        VStack {
            Picker("", selection: $PickerSelection) {
                Text("Selection 1").tag(0)
                Text("Selection 2").tag(1)
            }
            .pickerStyle(SegmentedPickerStyle()).padding(.horizontal, 100)
            .onReceive(Just(PickerSelection)) {
                UserDefaults.standard.set($0, forKey: "Picker")   // << here !!
            }

            Text("Hello World!")
        }
    }
}