我想将用户对当前语言的选择存储到UserDefaults。用户通过选择器选择他们喜欢的语言。然而,我不知道如何放置代码来更新UserDefaults。
下面是我的代码:
enum Language: Int, CaseIterable, Identifiable {
case en
case zh_hant
var description: String {
switch self {
case.en:
return "English"
case.zh_hant:
return "繁體中文"
}
}
var id: Int {
self.rawValue
}
}
然后在我的模型课上:
final class ModelData: ObservableObject {
// this is to be used as the default when the app is first launch.
// However, if the user choose the language, the default should be retrieve from UserDefaults
@Published var currentLanguage: Language = Language.en
}
和选择语言的用户界面:
struct ConfigurationView: View {
@EnvironmentObject var modelData: ModelData
let lang_title = ["Language", "語言"]
var body: some View {
List {
VStack {
HStack {
Text(lang_title[modelData.currentLanguage.rawValue]).font(.title2)
Spacer()
}
Picker("Language", selection: $modelData.currentLanguage) {
ForEach(Language.allCases, id: \.id) { language in
Text(language.description).tag(language)
}
}
.pickerStyle(SegmentedPickerStyle())
}
.padding()
}
}
}
我如何从UserDefaults加载所选语言并更新用户?
这里有一个可能的方法(存储/还原的值可以根据需要选择)
Picker("Language", selection: $modelData.currentLanguage) {
ForEach(Language.allCases, id: \.id) { language in
Text(language.description).tag(language)
}
}
.pickerStyle(SegmentedPickerStyle())
.onChange(of: modelData.currentLanguage) {
UserDefaults.standard.setValue($0.rawValue, forKey: "language")
}
和创建(或在init
中(如果需要一些解码))
final class ModelData: ObservableObject {
@Published var currentLanguage = Language(rawValue: UserDefaults.standard.value(forKey: "language") as? Int ?? 0)!
}
另外,您可以在ConfigurationView
视图中考虑AppStorage
属性包装。
您需要用相同的值重新设置它