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

问题描述

我有一个使用 CocoaPods 的项目.结果,我有一个包含两个项目的工作区:我的和 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-20 02:48