我写了一个简单的分类,用于处理与IB本地化相关的事务。
头文件看起来是这样的。
@interface UIView (Localization)
@property (nonatomic, strong) NSString *mainTextKey;
@property (nonatomic, strong) NSString *secondaryTextKey;
- (void)updateMainText;
- (void)updateSecondaryText;
@end
实现
@implementation UIView (Localization)
- (NSString *)mainTextKey{
return objc_getAssociatedObject(self, @selector(mainTextKey));
}
- (void)setMainTextKey:(NSString *)mainTextKey{
objc_setAssociatedObject(self, @selector(mainTextKey), mainTextKey, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
[self updateMainText];
}
- (NSString *)secondaryTextKey{
return objc_getAssociatedObject(self, @selector(secondaryTextKey));
}
- (void)setSecondaryTextKey:(NSString *)secondaryTextKey{
objc_setAssociatedObject(self, @selector(secondaryTextKey), secondaryTextKey, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
[self updateSecondaryText];
}
- (void)updateMainText{
if([self isKindOfClass:[UILabel class]]){
UILabel *label = (UILabel *)self;
label.text= NSLocalizedString(self.mainTextKey, nil) ;
}else if ([self isKindOfClass:[UIButton class]]){
UIButton *btn = (UIButton *)self;
[btn setTitle:NSLocalizedString(self.mainTextKey, nil) forState:UIControlStateNormal];
}
}
- (void)updateSecondaryText{
}
@end
基本用法:
- 创建一个类似于UIButton或UIlable的UIView元素
- 在UserDefinedAttributes中针对"mainTextKey"或"secondaryTextKey"键指定您的字符串键。
- 运行应用程序,它将从您的字符串文件加载适当的文本。
这篇文章没有经过任何校对,如有任何愚蠢的错误请谅解。