最近刚接手了一个直播的项目,但是面向的用户人群是境外华侨和各国人士,整个项目本身就很大。很无奈,但是还得弄啊。怎么办?我就用了一天将完整的整个项目实现了国际化。基础的我就不讲了,想了解的看《iOS之应用程序国际化》、《iOS国际化开发》。下面开始讲讲我的方法:
工具
由于也是第一次接触到国际化,抱着向前辈学习思想(其实我就是想偷懒
),找到了这个工具,这个可以支持中文和繁体文导出,用它你整个项目中的中文都可以获取到,我fork了这个项目并且在此项目的基础上修改了一下正则表达式,添加了支持xib,storyBoard,swift文件的支持,大家可以用这个国际化导出中文工具。
Demo效果
代码
只需要在项目中导入Categories文件夹,就可以实现项目国际化了。
主要的方法:
扩展NSBundle
#import "NSBundle+I18N.h"
#import <objc/runtime.h>
static const NSString *bundleKey = @"bundleKey";
@interface BundleEx : NSBundle
@end
@implementation BundleEx
- (NSString *)localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)tableName {
NSBundle *bundle = objc_getAssociatedObject(self, &bundleKey);
return bundle ? [bundle localizedStringForKey:key value:value table:tableName] : [super localizedStringForKey:key value:value table:tableName];
}
@end
@implementation NSBundle (I18N)
+ (void)setMainBundelLanguage:(NSString *)language {
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
object_setClass([NSBundle mainBundle], [BundleEx class]);
});
//设置关联
objc_setAssociatedObject([NSBundle mainBundle], &bundleKey, language ? [NSBundle bundleWithPath:[[NSBundle mainBundle] pathForResource:language ofType:@"lproj"]] : nil, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
+ (NSBundle *)getCurrentMainBundel {
NSString * currentLanguage = [[NSUserDefaults standardUserDefaults] objectForKey:@"AppleLanguages"][0];
NSString *path = [[ NSBundle mainBundle ] pathForResource:currentLanguage ofType:@"lproj" ];
NSBundle * current = [NSBundle bundleWithPath:path];
return current;
}
@end
扩展UILable
#import "UILabel+I18N.h"
#import <objc/runtime.h>
@implementation UILabel (I18N)
+(void)load {
SEL originalSelector = @selector(setText:);
SEL swizzledSelector = @selector(swizzled_setText:);
Method originMehtod = class_getInstanceMethod([self class], @selector(setText:));
Method otherMehtod = class_getInstanceMethod([self class], @selector(swizzled_setText:));
BOOL didAddMethod =
class_addMethod(self,
originalSelector,
method_getImplementation(otherMehtod),
method_getTypeEncoding(otherMehtod));
if (didAddMethod) {
class_replaceMethod(self,
swizzledSelector,
method_getImplementation(originMehtod),
method_getTypeEncoding(originMehtod));
}
else {
// 交换2个方法的实现
method_exchangeImplementations(otherMehtod, originMehtod);
}
}
- (void)swizzled_setText:(NSString *)string {
[self swizzled_setText:NSLocalizedString(string, nil)];
}
@end
扩展UIImage
#import "UIImage+I18N.h"
#import <objc/runtime.h>
@implementation UIImage (I18N)
+(void)load {
Method otherMehtod = class_getClassMethod(self, @selector(swizzled_imageNamed:));
Method originMehtod = class_getClassMethod(self, @selector(imageNamed:));
// 交换2个方法的实现
method_exchangeImplementations(otherMehtod, originMehtod);
}
+ (UIImage *)swizzled_imageNamed:(NSString *)name {
return [self swizzled_imageNamed:NSLocalizedString(name, nil)];
}
@end
源码
点击这里下载源代码
网友评论