[英]Load localized string from my app inside a static lib?
I have a project divided in layers, and the bottom one is included in the top one as a static lib. 我有一个项目,分为若干层,最下面的一个作为静态库包含在最上面的一个中。
The thing is that I need to localize a string in the static lib, using the translations present in my app (upper layer). 事情是,我需要使用应用程序(上层)中提供的翻译在静态库中本地化字符串。
Is this possible somehow? 这有可能吗?
The way I managed to do this is loading the strings from a bundle instead of using NSLocalizedString
: 我设法做到这一点的方法是从捆绑中加载字符串,而不是使用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];
}
You can create an LanguageAgent in your static library, add a bundle ressource in that library. 您可以在静态库中创建LanguageAgent,然后在该库中添加包资源。 Then use a function like this to get localizedString. 然后使用类似这样的函数来获取localizedString。 In my application, I separate language by different table (see picture below for a table named 'Dictionaire'. You can have more than 1 table in your languages bundle. 在我的应用程序中,我用不同的表来分隔语言(请参见下图以获取名为“ 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 @"[]";
}
}
My language bundle is similar like this: ('Dictionaire' = name of the table) 我的语言包是这样的:('Dictionaire'=表名)
Here is a sample of content in my Dictionnaire.strings for 'en.lproj': 这是我的Dictionnaire.strings中的“ en.lproj”内容样本:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.