13
votes

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
Hi Jelly! Is there a way of doing this from a storyboard instead of having to load the label's text using code?Felipe Ferri
Unfortunately I don't think it's possible. You'll have to do it from code.Jelly

1 Answers

8
votes

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).