使用故事板中的属性字符串本地化UILabel

时间:2016-02-29 03:17:22

标签: ios objective-c localization nsattributedstring

我有一个UILabel文本设置为"归因于"在故事板中。当我生成Main.strings文件以翻译成另一种语言时,不会出现此标签的文本。

我尝试通过复制对象ID手动将条目添加到Main.strings文件中。我尝试设置"文本"财产和" attributionText"属性,但是当我运行应用程序时,不使用已翻译的字符串。

那么,我如何将UILabel集本地化为"归因于"在故事板上?

1 个答案:

答案 0 :(得分:7)

我最终使用this answer作为参考,通过故事板和代码的组合来解决这个问题。

首先,我在故事板上使用的属性字符串只对整个字符串应用了1.5行间距,因此在代码上设置文本更容易,保留了故事板的标签格式。

故事板包含一个UILabel,其text属性设置为Attributed,高度为1.5行。

在我的视图控制器代码上,我有一个setupUI方法和UILabel的插座。

@interface MyClass ()
@property (weak, nonatomic) IBOutlet UILabel *aLabel;
@end

@implementation MyClass
- (void)setupUI {
    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithAttributedString:self.aLabel.attributedText];
    [attributedString.mutableString setString:NSLocalizedString(@"This is the label text which should be localisable.", "")];
    self.aLabel.attributedText = attributedString;
}
@end

使用上面的代码,变量attributionString存储故事板上设置的所有格式,因此当我更改attributionString文本时,我不必再次设置格式。当然,当我执行"导出本地化"时,标签文本出现在Localizable.strings上。命令。

如果referencedString的内部子字符串具有不同的格式,那么这也不会起作用。在这种情况下,格式化必须在代码上手动设置(或使用rtf文件,如Jelly评论中发布的答案所示)。