L'internationalisation peut se faire aisément à l'aide d'Xcode.
Le tutoriel qui suit est un bref exemple d'internationalisation d'une application.
La structure proposée est d'avoir un fichier .strings (clé->valeur) comprenant les différentes traductions du logiciel.
MyApp/English.lproj/MyApp.strings
MyApp/French.lproj/MyApp.strings
Xcode reconnaîtra alors qu'il s'agira du même fichier mais pour différentes langues.
Nous allons commencer par créer un nouveau projet :
Une fois le projet créé, ajoutez un nouveau fichier "strings" au projet :
Ajoutez ce fichier dans un sous-répertoire nommé "English.lproj" :
Le fichier est maintenant créé et Xcode l'a reconnu comme étant versionalisé en anglais :
Afficher les informations de ce fichier et cliquez sur le bouton "Add localization" :
Entrez ensuite "French" :
Xcode créera alors automatiquement un dossier French.lproj contenant le fichier de localisation.
Pour utiliser notre système de localisation il existe diverses fonctions/macros :
NSLocalizedString
NSLocalizedStringFromTable
NSLocalizedStringFromTableInBundle
NSLocalizedStringWithDefaultValue
Nous allons ici utiliser NSLocalizedString car elle utilise divers paramètres par défaut (une table nil correspond à la table par défaut : Localizable.strings)
Nous allons, lorsque la vue est lancée afficher un message d'alerte.
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
[super viewDidLoad];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"ALERT_TITLE_TEXT", @"The alert title")
message:NSLocalizedString(@"ALERT_MESSAGE_TEXT", @"The alert message")
delegate:self
cancelButtonTitle:NSLocalizedString(@"ALERT_CANCEL_TEXT", @"The alert cancel text")
otherButtonTitles:NSLocalizedString(@"ALERT_OK_TEXT", @"The alert ok text"),nil];
[alert show];
[alert release];
}
Voici le contenu du fichier .strings anglais pour l'exemple :
/* The alert title */
"ALERT_TITLE_TEXT" = "My title";
/* The alert message text */
"ALERT_MESSAGE_TEXT" = "My message";
/* The alert cancel text */
"ALERT_CANCEL_TEXT" = "Cancel";
/* The alert ok text */
"ALERT_OK_TEXT" = "OK";
Et la version française :
/* The alert title */
"ALERT_TITLE_TEXT" = "Mon titre";
/* The alert message text */
"ALERT_MESSAGE_TEXT" = "Mon message";
/* The alert cancel text */
"ALERT_CANCEL_TEXT" = "Annuler";
/* The alert ok text */
"ALERT_OK_TEXT" = "OK";
Voici le résultat :
