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