我寫了一個簡單的類別,用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{
//handle all cases one by one
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{
//handle all cases one by one
}
@end
基本用法:
- 創建一個UIView元素一樣的UIButton或UIlable
- 指定對鍵 「mainTextKey」 你的字符串鍵內UserDefinedAttributes或 「secondaryTextKey」 。
- 運行該應用程序,它會從你的字符串文件中加載正確的文本。
這是沒有任何證明的書面閱讀,原諒任何愚蠢的錯誤。
對於一個沒有經驗的iOS開發人員來說,實現國際化似乎有點複雜......但是在閱讀文檔和嘗試一個簡單的測試應用程序之後,它可能會變得更加清晰:)謝謝您的答案! –
Jacky,我有一個問題給你......如果我想從一開始就開始一個新的應用程序並將其國際化,是否需要「手動」或者我可以告訴Xcode以「國際化」應用?我對單視圖應用程序有一定的經驗,Xcode爲你準備了nib文件和其他東西,我想知道我是否能告訴Xcode以一種可以輕鬆國際化的方式準備項目。我希望我的問題是非常清楚的。 –
我已經看到有可能告訴Xcode國際化資源,所以我試圖國際化xxx-info.plist文件,但代碼無法編譯,因爲它確實不要在en.lproj目錄中查找它,而是在基本目錄中......我想我必須在理解如何正確管理這些東西之前仔細閱讀文檔..也許info.plist文件不需要是國際.. –