JayVDiyk
JayVDiyk

Reputation: 4487

Change Language inside Application

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

Answers (2)

Darko
Darko

Reputation: 9845

If you want to do your own solution then one of the many possible ways would be to:

  1. Create your own singleton Localization Manager Class
  2. 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

ttarik
ttarik

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:

  1. Create a 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).
  2. Add your desired languages to your app's project (Project > [App name] > Localizations > "+" button). This will present a prompt containing your project's localizable files (strings files and storyboards) - you'll probably want to select all of them.
  3. Select your Localizable.strings file, and in the Utilities (right side) menu, under Localization, click Localize. Select English as your starting language (assuming your app is currently in English).
  4. You'll now have a list of your localizable languages with checkboxes. Enable each language, which will create a language-specific version of Localizable.strings.
  5. All of your localized files, including Localizable.strings and your Storyboards, will now have a arrow in the Project Navigator. If you click these arrows to expand, you can edit each of your localizations for these files.
  6. Done! Easy. You can test this in the Simulator or on your device by changing your device's language.

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

Related Questions