繁体   English   中英

从我的应用程序加载本地化的字符串到静态库中?

[英]Load localized string from my app inside a static lib?

我有一个项目,分为若干层,最下面的一个作为静态库包含在最上面的一个中。

事情是,我需要使用应用程序(上层)中提供的翻译在静态库中本地化字符串。

这有可能吗?

我设法做到这一点的方法是从捆绑中加载字符串,而不是使用NSLocalizedString

+ (NSString *)getTranslationFromAppBundleForString:(NSString *)originalText {

    NSString * lang = [[NSLocale preferredLanguages] objectAtIndex:0];
    NSString * bundlePath = [[NSBundle mainBundle] pathForResource:lang ofType:@"lproj"];
    NSBundle * bundle = [NSBundle bundleWithPath:bundlePath];

    return [bundle localizedStringForKey:originalText value:originalText table:nil];
}

您可以在静态库中创建LanguageAgent,然后在该库中添加包资源。 然后使用类似这样的函数来获取localizedString。 在我的应用程序中,我用不同的表来分隔语言(请参见下图以获取名为“ Dictionaire”的表。在您的语言包中可以有多个表。

-(NSString*) myLocalizedStringForKey:(NSString*) key ofTable:(NSString*)tableName {
    //I save selected language in my NSUserDefaults.
    NSString *selectedLanguage = [[NSUserDefaults standardUserDefaults] stringForKey:@"DefaultLanguage"];

    if (selectedLanguage == nil) {
        [[NSUserDefaults standardUserDefaults] setValue:@"en" forKey:@"DefaultLanguage"];
        [[NSUserDefaults standardUserDefaults] synchronize];
        selectedLanguage = [[NSUserDefaults standardUserDefaults] stringForKey:@"DefaultLanguage"];
     }

    NSString *langBundleNew = [[NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingFormat:@"/langs/Languages.bundle/%@.lproj/",selectedLanguage]; //use your path to the Languages.bundle here. 

    if ([[NSFileManager defaultManager] fileExistsAtPath:langBundleNew]) {
        NSBundle *aBundle = (NSBundle*)[self.dictLangueBundle objectForKey:selectedLanguage];
         NSString* str=[aBundle localizedStringForKey:key value:@"[string not defined]" table:tableName];
         return str;
    } else {
        return @"[]";
    }
}

我的语言包是这样的:('Dictionaire'=表名)

在此处输入图片说明

这是我的Dictionnaire.strings中的“ en.lproj”内容样本:

在此处输入图片说明

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM