【问题标题】:SwiftUI: How I can save picker data with UserDefaults?SwiftUI:如何使用 UserDefaults 保存选择器数据?
【发布时间】:2020-09-13 18:40:17
【问题描述】:

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

【问题讨论】:

    标签: swift xcode swiftui


    【解决方案1】:

    您可以在Just 发布者的帮助下使用.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!")
            }
        }
    }
    

    【讨论】:

    • 你注意到上面的import Combine了吗?
    猜你喜欢
    • 2020-04-03
    • 1970-01-01
    • 2022-01-18
    • 2020-11-08
    • 2020-03-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-22
    相关资源
    最近更新 更多