SwiftUI: Como posso salvar dados do seletor com UserDefaults?

Sep 13 2020

Sou novo no SwiftUI e desejo salvar a escolha do usuário no seletor. Eu sei que preciso de UserDefaults para isso, mas não sei como usar UserDefaults neste caso.

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!")
    }
}

Respostas

2 Asperi Sep 13 2020 at 18:45

Você pode usar .onReceivecom a ajuda do Justeditor (para ser compatível com 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!")
        }
    }
}