You need to save the application language selected by user in userDefaults by example, this example is using the third party library SwiftyUserDefaults
Using this way you need to add the .strings with the "Localizable_" + initials of language of regular localization way, example
your .string file for Spanish should be named
"Localizable_es" but you can customize that in code too
this are the steps:
Save the app language selected by the user:
func setupAppLanguage(lang:String) {
Defaults[.appLanguage] = lang
}
Get saved language:
static func getCurrentLang() ->String
{
if(Defaults[.appLanguage] == nil)
{
if(NSLocale.current.languageCode == nil)
{
return "en"
}
return NSLocale.current.languageCode!
}else
{
return Defaults[.appLanguage] as String!
}
}
Get localized tableName language:
static func getLocalizedTableName() ->String
{
return "Localizable_\(Client.getCurrentLang())"
}
Method to localize:
//MARK: Localization Util
static func getLocalizedText(toLocalizeText:String) ->String{
return NSLocalizedString(toLocalizeText,tableName: Client.getLocalizedTableName(), comment: "")
}
Then you can use the getLocalizedText
method the same way as you use NSLocalizedString
, replacing it
Example of use
self.labelText.text = Client.getLocalizedText(toLocalizeText: "k_glossary")