代码
只需要在项目中导入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