【问题标题】:Is there an option to implicitly localise labels in Interfacebuilder是否有选项可以在 Interface Builder 中隐式本地化标签
【发布时间】:2011-09-14 07:48:01
【问题描述】:
在一篇博文中,我偶然发现了一个字符串文件,它看起来像这样:
// de.lproj/Localizable.strings
"This is the title" = "Das ist der Titel"
在我看来,Interface builder 中的实际标签似乎是由编译器处理的,因此不再需要使用 NSLocalizedString(@"SOME_IDENTIFIER", @""); 进行显式翻译。
我现在的问题是,是否有某种捷径,或者我是否需要在我的视图中本地化所有单独的标签,例如在awakeFromNib 方法中。
【问题讨论】:
标签:
ios
xcode
internationalization
interface-builder
【解决方案1】:
我想出了一种半自动化流程的方法,这样我就不必这样做了:
label1.text = NSLocalizedString(@"label1_key", @"");
label2.text = NSLocalizedString(@"label2_key", @"");
....
labeln.text = NSLocalizedString(@"labeln_key", @"");
所以对于所有应该本地化的标签,我在 IB 中将它们的文本设置为 __KeyForLabelX。然后在 viewcontroller 的 viewWillAppear 方法中,我遍历视图上的项目并将文本设置为本地化值:
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, @"");
}
}
}
我的 .strings 文件如下所示:
"TranslationPrefixKeyForLabelX" = "Translation of Label X";
更新:为了进一步调整机制,您还可以检查其他UIViews,如UIButtons、UITextFields(包括提示文本)等。