Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change the text of an attributed UILabel without losing the formatting?

In the storyboard I layout a set of labels with various formatting options.

Then I do:

label.text = @"Set programmatically";

And all formatting is lost! This works fine in iOS5.

There must be a way of just updating the text string without recoding all the formatting?!

label.attributedText.string 

is read only.

Thanks in advance.

like image 762
lewis Avatar asked Oct 03 '12 10:10

lewis


1 Answers

You can extract the attributes as a dictionary with:

NSDictionary *attributes = [(NSAttributedString *)label.attributedText attributesAtIndex:0 effectiveRange:NULL];

Then add them back with the new text:

label.attributedText = [[NSAttributedString alloc] initWithString:@"Some text" attributes:attributes];

This assumes the label has text in it, otherwise you'll crash so you should probably perform a check on that first with:

if ([self.label.attributedText length]) {...}
like image 163
josef Avatar answered Sep 27 '22 17:09

josef