use*_*136 19 localization ios cocoapods
我有一个使用CocoaPods的项目.因此,我有一个包含两个项目的工作区:mine和Pods.
Pods包含我想要本地化的代码,我.strings在Pod中创建了文件.但是,NSLocalizedString无法加载这些字符串.我怀疑这.strings是因为文件不在主包中,但是没有Pod包,因为它被编译成静态库.
有没有比在我的主项目中更好的方法来本地化CocoaPods项目中的代码?
Riv*_*era 12
NSLocalizedString只是调用NSBundle,localizedStringForKey:value:table:所以我编写了一个NSBundle类,以便查看几个包(在iOS中只是文件夹):
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;
}
Run Code Online (Sandbox Code Playgroud)
然后NSLocalizedString在我的前缀文件中重新定义了宏:
#undef NSLocalizedString
#define NSLocalizedString(key, comment) \
[NSBundle localizedStringForKey:key value:nil table:@"MyStringsFile" backupBundle:AlternativeBundleInsideMain]
Run Code Online (Sandbox Code Playgroud)
如果需要,其他宏也一样(即NSLocalizedStringWithDefaultValue)
@Rivera Swift 2.0版本:
static let kLocalizedStringNotFound = "kLocalizedStringNotFound"
static func localizedStringForKey(key:String,
value:String?,
table:String?,
bundle:NSBundle?) -> String {
// First try main bundle
var string:String = NSBundle.mainBundle().localizedStringForKey(key, value: kLocalizedStringNotFound, table: table)
// Then try the backup bundle
if string == kLocalizedStringNotFound {
string = bundle!.localizedStringForKey(key, value: kLocalizedStringNotFound, table: table)
}
// Still not found?
if string == kLocalizedStringNotFound {
print("No localized string for '\(key)' in '\(table)'")
if let value = value {
string = value.characters.count > 0 ? value : key
} else {
string = key
}
}
return string;
}
Run Code Online (Sandbox Code Playgroud)
您不应将任何文件放入 Pods 项目中,因为该pod命令将一次又一次地重新创建项目。
所以把字符串文件放到自己的项目中。
如果您想在自己的 Pod中发送本地化字符串文件,您应该将其包含在捆绑包中,并确保该捆绑包将安装在您的 Podspec 文件中。
例如:
def s.post_install(target)
puts "\nGenerating YOURPOD resources bundle\n".yellow if config.verbose?
Dir.chdir File.join(config.project_pods_root, 'YOURPOD') do
command = "xcodebuild -project YOURPOD.xcodeproj -target YOURPODResources CONFIGURATION_BUILD_DIR=../Resources"
command << " 2>&1 > /dev/null" unless config.verbose?
unless system(command)
raise ::Pod::Informative, "Failed to generate YOURPOD resources bundle"
end
File.open(File.join(config.project_pods_root, target.target_definition.copy_resources_script_name), 'a') do |file|
file.puts "install_resource 'Resources/YOURPODResources.bundle'"
end
end
end
Run Code Online (Sandbox Code Playgroud)