Localising a UILabel with attributed string from a Storyboard

佐手、 提交于 2021-02-18 20:39:51

问题


I have a UILabel with text set as "attributed" in a storyboard. When I generate the Main.strings file for translating into a different language the text for this label does not appear.

I tried to add manually an entry into the Main.strings file by copying the object id. I tried setting the "text" property and the "attributedText" property but when I run the app the translated string is not used.

So, how do I localise an UILabel set as "attributed" on a storyboard?


回答1:


I ended up solving this with a combination of storyboard and code, using this answer as a reference.

To start with, the attributed string I used on the storyboard just applied a 1.5 line spacing to the whole string, so it was easier to set the text on code preserving the storyboard's label formatting.

The storyboard contains a UILabel with the text property set as Attributed and a 1.5 line height multiple.

On my view controller code I have a setupUI method and a outlet for that 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

With the above code, the variable attributedString stores all the formatting set on the storyboard, so when I change the attributedString text I don't have to set the formatting again. And, of, course, the label text appears on the Localizable.strings when I execute the "Export for Localizations" command.

This wouldn't work as well if the attributedString had different formatting for its internal substrings. In that case the formatting would have to be set up manually on code (or using rtf files as suggested by the answer posted on the comment by Jelly).



来源:https://stackoverflow.com/questions/35691380/localising-a-uilabel-with-attributed-string-from-a-storyboard

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!