Ami*_*ark 3 iphone xcode localization localizable.strings nslocalizedstring
是否可以使用NSLocalizedString基础结构(基于localizable.strings)和自定义的"本地化"?
问题是,有些语言对男性和女性有不同的措辞.我想在首次启动时询问用户的性别,然后使用相应的短语.当然,两者都基于相同的语言.我可以使用自己的代码来完成它,但如果可能的话,我宁愿这么做.
这是我的Custom实现,它使用NSLocalizedString,它使用comment作为默认值:
(NSLocalizedStringWithDefaultValue与genstring无法正常工作,这就是我提出此解决方案的原因)
1.在预编译的头文件(.pch文件)中,重新定义'NSLocalizedString'宏:
// cutom NSLocalizedString that use macro comment as default value
#import "LocalizationHandlerUtil.h"
#undef NSLocalizedString
#define NSLocalizedString(key,_comment) [[LocalizationHandlerUtil singleton] localizedString:key comment:_comment]
Run Code Online (Sandbox Code Playgroud)
2.创建一个类来实现本地化处理程序
#import "LocalizationHandlerUtil.h"
@implementation LocalizationHandlerUtil
static LocalizationHandlerUtil * singleton = nil;
+ (LocalizationHandlerUtil *)singleton
{
return singleton;
}
__attribute__((constructor))
static void staticInit_singleton()
{
singleton = [[LocalizationHandlerUtil alloc] init];
}
- (NSString *)localizedString:(NSString *)key comment:(NSString *)comment
{
// default localized string loading
NSString * localizedString = [[NSBundle mainBundle] localizedStringForKey:key value:key table:nil];
// if (value == key) and comment is not nil -> returns comment
if([localizedString isEqualToString:key] && comment !=nil)
return comment;
return localizedString;
}
@end
Run Code Online (Sandbox Code Playgroud)
3.使用它!
确保在App Build Phases中添加Run脚本,以便在每次构建时更新Localizable.strings文件,即在Localized.strings文件中添加新的本地化字符串:
我的构建阶段脚本是一个shell脚本:
Shell: /bin/sh
Shell script content: find . -name \*.m | xargs genstrings -o MyProjectFolder
Run Code Online (Sandbox Code Playgroud)
因此,当您在代码中添加此新行时:
self.title = NSLocalizedString(@"view_settings_title", @"Settings");
Run Code Online (Sandbox Code Playgroud)
然后执行构建,您的./Localizable.scripts文件将包含以下新行:
/* Settings */
"view_settings_title" = "view_settings_title";
Run Code Online (Sandbox Code Playgroud)
由于'view_settings_title'的key ==值,自定义LocalizedStringHandler将返回注释,即'Settings'
Voilà:-)
| 归档时间: |
|
| 查看次数: |
6134 次 |
| 最近记录: |