This is how I did it. I created an extension on String class and created a localized
variable which gets the string values from my Localizable.strings
files of a language
public extension String {
var localized: String {
// currentLanguageCode is e.g. "en" or "nl"
let path = Bundle.main.path(forResource: LocalizationService.shared.currentLanguageCode, ofType: "lproj")
let bundle = Bundle(path: path!)
return NSLocalizedString(self, tableName: nil, bundle: bundle!, value: "", comment: "")
}
}
Then everywhere in my code when I want to assign localized string values I do:
titleLabel.text = "settings_label_userProfile".localized
When user changes the language e.g. in my settings section, LocalizationService
sets a different language code and from then on localized
property will return the values of that language code. You need to make sure that the UI is reloaded if it's still displaying the previous language strings.
EDIT:
This solution will only work if you set your localizable strings programatically.