SwiftUI:如何使用UserDefaults保存选择器数据?

时间:2020-09-13 18:40:17

标签: swift xcode swiftui

我是SwiftUI的新手,想保存选择器中的用户选择。我知道我需要 UserDefaults ,但是在这种情况下,我不知道如何使用 UserDefaults

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 个答案:

答案 0 :(得分:2)

您可以在Just发布者的帮助下使用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!") } } } (与iOS 13 *兼容)

{{1}}