Reputation: 4487
In my iOS app, I am planning to let user to change the language.
What is the best approach to accomplish this?
Currently all my String is inside a struct. But I am wondering what is the best approach to change language according to what user choose.
Any suggestions?
Upvotes: 1
Views: 1196
Reputation: 9845
If you want to do your own solution then one of the many possible ways would be to:
Add every UILabel in the App into a dictionary which holds an UILabel and the key string. Then just:
for label in labels {
If let label = LocMan.sharedInst.labels["some Key"] {
label.text = NSLocalizedString("some Key" comment: "")
}
}
For other text classes you should do the same.
Upvotes: 1
Reputation: 3853
The most common way to do this is not to allow the user to change the language within the app itself, but rather let iOS do this for you.
Here's a good tutorial to start localizing your app's strings using NSLocalizedString
. You should follow the whole tutorial as it has a bunch of useful information about localization, but here's a brief overview of what you have to do:
Localizable.strings
file for your project. This file follows the format "Hello" = "Hello";
, where the key on the left will be the string's identifier for NSLocalizableString
and the value on the right is the localized string. In this case, you would replace any code references to this string (for example, @"Hello"
) with NSLocalizedString(@"Hello", nil)
.Once this has been completed, your app will load strings from whichever supported language the user has selected in their device settings.
This question also has some useful tips for localizing an existing app - in particular, mass-replacing existing strings with NSLocalizedString
.
Upvotes: 2