Reputation: 39
My task is to change the language settings from English to two other languages. I added those languages in the Localization and creates Localizable string file where I added those three languages, however, I don't know how to apply this changes. I need to pick a language from a picker, press "save" and apply those changes. Also I have a button "Reset" which will turn the app back to English. I would like to see the exact code of how to apply it< if possible, please
Upvotes: 0
Views: 620
Reputation: 16341
You just need to simply set the language
key in the UserDefaults
to alter the language of the app. Although, the views will have to be reloaded to apply these changes to the strings that are already being loaded.
Here's a working example that you can use:
enum Language: String, CaseIterable {
case english, german, french
var code: String {
switch self {
case .english: return "en"
case .german: return "de"
case .french: return "fr"
}
}
static var selected: Language {
set {
UserDefaults.standard.set([newValue.code], forKey: "AppleLanguages")
UserDefaults.standard.set(newValue.rawValue, forKey: "language")
}
get {
Language(rawValue: UserDefaults.standard.string(forKey: "language") ?? "") ?? .english
}
}
}
Usage:
Language.selected = .french
You can modify the above API according to your needs.
Upvotes: 1