简体   繁体   English

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

[英]SwiftUI: How I can save picker data with UserDefaults?

I'm new in SwiftUI and want to save the user choice from picker.我是 SwiftUI 的新手,想从选择器中保存用户选择。 I know I need UserDefaults for that, but I don't know how to use UserDefaults in this case.我知道我需要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!")
    }
}

You can use .onReceive with help of Just publisher (to be compatible with iOS 13*)您可以在Just Publisher 的帮助下使用.onReceive (与 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!")
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM