Swift:How to Change Language Inside App

Swift : How to change language inside app?

found my answer :

NSUserDefaults.standardUserDefaults().setObject(["language identifier"], forKey: "AppleLanguages") 
NSUserDefaults.standardUserDefaults().synchronize()

unfortunately user must restart the app!
if anyone could find a solution to not restart the application please inform me.

Change language inside the app using Picker view

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.



Related Topics



Leave a reply



Submit