UILabel appearance font and attributed string font

nebs picture nebs · Jul 30, 2014 · Viewed 11.2k times · Source

In my app I have a global custom font applied to all labels like so:

UIFont *font = [UIFont fontWithName:kMyFontName size:15.0]; 
[[UILabel appearance] setFont:font];

This works fine. However, in some cases I want to be able to specify a different font for a specific region of a UILabel string.

So I have something like this:

NSString *string = @"Foo Bar Baz";
UIFont *boldFont = [UIFont fontWithName:kMyBoldFontName size:15.0]; 
NSMutableAttributedString *attrString = [[NSMutableAttributedString alloc] initWithString:string];
[attrString setAttributes:@{ NSFontAttributeName: boldFont } range:NSMakeRange(0, 3)];
self.myLabel.attributedText = attrString;

However this doesn't seem to work. I expect the "Foo" to be bold, but the entire string just has the default font. It's as if the bold font is not applied at all and is being overwritten by the font set on the UILabel appearance proxy.

When I remove the UILabel appearance line then it works fine (I can see part of the string in bold). Basically I want to have my custom font applied to the label but a separate font applied to a different region of the string. Normally this works fine with attributed strings but for some reason setting the UILabel appearance font disables this functionality (or so it seems).

  • Expected results: "Foo Bar Baz"
  • Actual results: "Foo Bar Baz"

If I remove the [[UILabel appearance] setFont:] line then it works:

  • "Foo Bar Baz"

(but the custom font is not set on the rest of the string).

So my question is: Is there a way to specify a single font to use as the default app-wide but still be able to partially override that using attributed strings?

Also if someone can explain to me why this is not working I'd appreciate it.

Answer

ksysu picture ksysu · Jan 30, 2015

Set font and textColor to nil just before setting attributed string.