user3278013 user3278013 - 1 year ago 674
iOS Question

Change Language in the app programmatically

How to change the language in Xcode 5

I have 3 buttons on the


This are:

  • English

  • Chinese Simplified

  • Bahasa Malaysia

Here is code:

#import <UIKit/UIKit.h>
@interface ChangeLanguageViewController :UIViewController


[[NSUSerDefaults standardUSerDefaults] setObject:[NSArray arrayWithObjects:@"en", @"zh-Hans", @"ms", nil] forKey:@"AppleLanguage"];
[[NSUSerDefaults standardUSerDefaults] setObject:[NSArray arrayWithObjects:@"zh-Hans", @"ms", @"en", nil] forKey:@"AppleLanguage"];
[[NSUSerDefaults standardUSerDefaults] setObject:[NSArray arrayWithObjects:@"ms",@"en",@"zh-Hans", nil] forKey:@"AppleLanguage"];

I want to see the language change when the user presses a button and it will not kill the application but it changes the language of the app inside

Answer Source

Usually when you support official languages that Apple supports in iOS, there is no reason to provide language switching within the app, just properly set up translations in your project and interface language will automatically switch with the system. But since you want it from the app, there are few ways to go about this:

1) You could force a specific language for just your app with the following code:

[[NSUserDefaults standardUserDefaults] setObject:[NSArray arrayWithObjects:@"zh-Hans", @"en", @"fr", nil] forKey:@"AppleLanguages"];
[[NSUserDefaults standardUserDefaults] synchronize];

I would suggest putting this code inside main.m file in "int main" function just before the "return UIApplicationMain". But this method requires you to kill the app or tell user to restart the app for it to take effect.

You can kill the app without having user to force quit the app using exit(0), but make sure user has chance to abort the action with UIAlertView or similar, or Apple might reject your app.

2) Alternative is implementing your own localization logic, where you just take translations from your own language file. One way is this example which takes translations from official lproj files. This way you can change the language on the fly without a restart, but you have to manually load all label texts from the code. When you change the translation, you have to repopulate the text on screen.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download