Dec 19, 2008

(iPhone) How to localize your application

iPhone 3G embeds several language setting, it is pretty cool to write an application which has multi language support. Here are 2 solutions we could use to set an UIButton bt's title:

First:
- Find the device default language

NSUserDefaults* defs = [NSUserDefaults standardUserDefaults];
NSArray* languages = [defs objectForKey:@"AppleLanguages"];
NSString* preferredLang = [languages objectAtIndex:0];

preferredLang returns the default language, it looks like: "en" for English, "fr" for French, "zh-Hans" for Chinese Simp, "zh-Hant" for Chinese Trad etc.

- Set up the text by different language

if ([preferredLang isEqualToString:@"en"]) {
[bt setTitle:@"Hello" forState:UIControlStateNormal];
}
else if ([preferredLang isEqualToString:@"fr"]) {
[bt setTitle:@"Bonjour" forState:UIControlStateNormal];
}
.......
else if ([preferredLang isEqualToString:@"zh-Hans"]) {
[bt setTitle:@"你好" forState:UIControlStateNormal];
}

Second:
- Create a strings file for your project (Add-New File-Strings File), Localizable.strings is a default strings file name, of course you can use the other names

- Make File Localizable: "Get Info" your strings file and click "Make File Localizable" on the left-bottom. You will see "English" shows on the Localizations list, and you can add the other languages by clicking "Add Localization". There are only 4 languages on the default list "English; French, Japnese and German". For the chinese, you should enter "zh_CN" for Chinese Simp and "zh_TW" for Chinese Trad, be careful it is different compare the first solution. After you have done this, there are several files under your strings file.

- Add the keys and values in the languages files. The format is:
in English
"hello" = "Hello !";

in French
"hello" = "Bonjour !";
etc.

Use the same keys for every language and just change the values. The iPhone will detect its language setting to load the right language file.

- Get the right text. If your strings file's name is Localizable, use NSLocalizedString(@"hello", nil) to get the value of "hello", if you use the other name, you should use NSLocalizedStringFromTable(@"hello", @"File name', nil) to return the text.

So the set bt's title, there is only one line of code:

[bt setTitle:NSLocalizedString(@"hello", nil) forState:UIControlStateNormal];

No comments: