PeterD PeterD - 5 months ago 37
iOS Question

Changing UILabel text but keeping the rest of the attributes

I have a UILabel in my ViewController created using storyboards. The font, size and color of the label's text, its alignment - all set in the storyboard. The label in the storyboard is connected to the outlet in my file called p_patientNameLbl.

Now I am trying to change the text of the label programatically, like this:

[self.p_patientNameLbl setText:@"Vasya"];


I could not see the new text, until I realized that the original label in the storyboard was white on black background, but apparently after I changed the label's text as above, all the font attributes have been reset and now it was a black text on black background, and therefore not seen. Once I set the color programmatically:

[self.p_patientNameLbl setTextColor:[UIColor whiteColor]];


I could see the new label, but all the rest of the font attributes and alignment were still wrong.

Is there a way to change only the text of the label without having then programmatically to set all the rest of the attributes? I would imagine there must be a way, since I don't want to be formatting my interface in the code!

Answer

This is happening because you're telling Interface builder to take a label that had pre-defined attributes set on its text and replace this attributed text with plain text. Instead of setText, or setTextColor you have to use setAttributedText and specify the attributes that you wish to pass to the attributed string.

Here's an example of how to apply an attributed string to your label programmatically. I'm not aware of any better way, but using this, you can make changes to the text or text color and as long as you set your other attributes along with them, all changes will be applied correctly.

[myLabel setAttributedText:[self myLabelAttributes:@"Some awesome text!"]];

....................

- (NSMutableAttributedString *)myLabelAttributes:(NSString *)input
{
    NSMutableAttributedString *labelAttributes = [[NSMutableAttributedString alloc] initWithString:input];

    [labelAttributes addAttribute:NSStrokeWidthAttributeName value:[NSNumber numberWithFloat:-5.0] range:NSMakeRange(0, labelAttributes.length)];
    [labelAttributes addAttribute:NSStrokeColorAttributeName value:[UIColor blackColor] range:NSMakeRange(0, labelAttributes.length)];
    [labelAttributes addAttribute:NSForegroundColorAttributeName value:[UIColor whiteColor] range:NSMakeRange(0, labelAttributes.length)];

    return labelAttributes;
}