gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 08:55:04 25 4
gpt4 key购买 nike

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

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

最佳答案

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

关于SwiftUI:如何使用 UserDefaults 保存选择器数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63874303/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com