Somewhere in a blog post I stumbled upon a strings file which looked like this:
// de.lproj/Localizable.strings
"This is the title" = "Das ist der Titel"
To me this looked like the actual labels in Interface builder were processed by the compiler so that no explicit translations using NSLocalizedString(@"SOME_IDENTIFIER", @"");
would be necessary any more.
My question now, is whether there is some kind of shortcut or do I need to localise all my individual labels on my view e.g. in the awakeFromNib
method.
I have figured out a way to semi-automate the process so that I don't have to do this:
label1.text = NSLocalizedString(@"label1_key", @"");
label2.text = NSLocalizedString(@"label2_key", @"");
....
labeln.text = NSLocalizedString(@"labeln_key", @"");
So for all labels which should be localised I set their text to __KeyForLabelX
in IB. Then in the viewWillAppear
method of the viewcontroller I loop through the items on the view and set the text to the localized value:
for (UIView *view in self.view){
if([view isMemberOfClass:[UILabel class]]){
UILabel *l = (UILabel *)view;
BOOL shouldTranslate = [l.text rangeOfString:@"__"].location != NSNotFound;
NSString *key = [l.text stringByReplacingOccurrencesOfString:@"__" withString:@"TranslationPrefix"];
if (shouldTranslate){
l.text = NSLocalizedString(key, @"");
}
}
}
My .strings file then look like this:
"TranslationPrefixKeyForLabelX" = "Translation of Label X";
Update: To further adapt the mechanism you could also check for other UIView
s like UIButtons
, UITextField
s (including prompt text) etc.