Is there an option to implicitly localise labels in Interfacebuilder

醉酒当歌 提交于 2019-12-11 06:45:07

问题


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.


回答1:


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 UIViews like UIButtons, UITextFields (including prompt text) etc.



来源:https://stackoverflow.com/questions/7412906/is-there-an-option-to-implicitly-localise-labels-in-interfacebuilder

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!