使用 Storyboard 中的属性字符串本地化 UILabel
Localising a UILabel with attributed string from a Storyboard
我有一个 UILabel,其文本在故事板中设置为 "attributed"。当我生成用于翻译成不同语言的 Main.strings 文件时,此标签的文本没有出现。
我试图通过复制对象 ID 手动将条目添加到 Main.strings 文件中。我尝试设置 "text" 属性 和 "attributedText" 属性 但是当我 运行 应用程序时,未使用翻译后的字符串。
那么,如何在故事板上本地化设置为 "attributed" 的 UILabel?
我最终结合故事板和代码解决了这个问题,使用 作为参考。
首先,我在情节提要上使用的属性字符串只是对整个字符串应用了 1.5 行间距,因此在代码中设置文本更容易,同时保留情节提要的标签格式。
故事板包含一个 UILabel,其文本 属性 设置为 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
使用上面的代码,变量 attributedString 存储故事板上设置的所有格式,因此当我更改 attributedString 文本时,我不必再次设置格式。当然,当我执行 "Export for Localizations" 命令时,标签文本出现在 Localizable.strings 上。
如果 attributedString 的内部子字符串具有不同的格式,这将无法正常工作。在这种情况下,必须在代码上手动设置格式(或使用 Jelly 在评论中发布的答案所建议的 rtf 文件)。
我有一个 UILabel,其文本在故事板中设置为 "attributed"。当我生成用于翻译成不同语言的 Main.strings 文件时,此标签的文本没有出现。
我试图通过复制对象 ID 手动将条目添加到 Main.strings 文件中。我尝试设置 "text" 属性 和 "attributedText" 属性 但是当我 运行 应用程序时,未使用翻译后的字符串。
那么,如何在故事板上本地化设置为 "attributed" 的 UILabel?
我最终结合故事板和代码解决了这个问题,使用
首先,我在情节提要上使用的属性字符串只是对整个字符串应用了 1.5 行间距,因此在代码中设置文本更容易,同时保留情节提要的标签格式。
故事板包含一个 UILabel,其文本 属性 设置为 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
使用上面的代码,变量 attributedString 存储故事板上设置的所有格式,因此当我更改 attributedString 文本时,我不必再次设置格式。当然,当我执行 "Export for Localizations" 命令时,标签文本出现在 Localizable.strings 上。
如果 attributedString 的内部子字符串具有不同的格式,这将无法正常工作。在这种情况下,必须在代码上手动设置格式(或使用 Jelly 在评论中发布的答案所建议的 rtf 文件)。