本地化和CocoaPods [英] Localization and CocoaPods

查看:276
本文介绍了本地化和CocoaPods的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用CocoaPods的项目。因此,我有一个包含两个项目的工作区:mine和Pods。

I have a project that uses CocoaPods. As a result, I have a workspace which contains two projects: mine and Pods.

Pods包含我想要本地化的代码,我在Pod中创建了 .strings 文件。但是, NSLocalizedString 无法加载这些字符串。我怀疑这是因为 .strings 文件不在主包中,但是没有Pod包,因为它被编译成静态库。

Pods contains code which I'd like to localize, and I've created .strings files in Pod. However, NSLocalizedString fails to load these strings. I suspect this happens because the .strings file is not in the main bundle, but there's no Pod bundle, because it is compiled into a static library.

有没有比在我的主项目中更好的方法来本地化CocoaPods项目中的代码?

Is there a better way to localize code in a CocoaPods project than in my main project?

推荐答案

NSLocalizedString 只调用NSBundle的 localizedStringForKey:value:table:所以我写了一个NSBundle类,以便查看几个包(在iOS中只是文件夹):

NSLocalizedString just invokes NSBundle's localizedStringForKey:value:table: so I wrote a NSBundle category to enable looking into several bundles (which in iOS are just folders):

NSString * const kLocalizedStringNotFound = @"kLocalizedStringNotFound";

+ (NSString *)localizedStringForKey:(NSString *)key
                              value:(NSString *)value
                              table:(NSString *)tableName
                       backupBundle:(NSBundle *)bundle
{
    // First try main bundle
    NSString * string = [[NSBundle mainBundle] localizedStringForKey:key
                                                               value:kLocalizedStringNotFound
                                                               table:tableName];

    // Then try the backup bundle
    if ([string isEqualToString:kLocalizedStringNotFound])
    {
        string = [bundle localizedStringForKey:key
                                         value:kLocalizedStringNotFound
                                         table:tableName];
    }

    // Still not found?
    if ([string isEqualToString:kLocalizedStringNotFound])
    {
        NSLog(@"No localized string for '%@' in '%@'", key, tableName);
        string = value.length > 0 ? value : key;
    }

    return string;
}

然后重新定义 NSLocalizedString 我的前缀文件中的宏:

Then redefined NSLocalizedString macro in my prefix file:

#undef  NSLocalizedString
#define NSLocalizedString(key, comment) \
[NSBundle localizedStringForKey:key value:nil table:@"MyStringsFile" backupBundle:AlternativeBundleInsideMain]

相同其他宏(如果需要)(即 NSLocalizedStringWithDefaultValue

The same for other macros if needed (i.e. NSLocalizedStringWithDefaultValue)

这篇关于本地化和CocoaPods的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆