UILabel外观字体和属性字符串字体

neb*_*ebs 14 objective-c nsattributedstring uilabel ios uiappearance

在我的应用程序中,我将全局自定义字体应用于所有标签,如下所示:

UIFont *font = [UIFont fontWithName:kMyFontName size:15.0]; 
[[UILabel appearance] setFont:font];
Run Code Online (Sandbox Code Playgroud)

这很好用.但是,在某些情况下,我希望能够为UILabel字符串的特定区域指定不同的字体.

所以我有这样的事情:

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;
Run Code Online (Sandbox Code Playgroud)

然而,这似乎不起作用.我希望"Foo"是粗体,但整个字符串只有默认字体.就好像粗体字体根本没有应用,并且被UILabel外观代理上的字体集覆盖.

当我删除UILabel外观线然后它工作正常(我可以看到粗体字符串的一部分).基本上我想将自定义字体应用于标签,但是应用于字符串的不同区域的单独字体.通常这适用于属性字符串但由于某种原因设置UILabel外观字体禁用此功能(或似乎如此).

  • 预期成果:" Foo Bar Baz"
  • 实际结果:"Foo Bar Baz"

如果我删除该[[UILabel appearance] setFont:]行,那么它的工作原理:

  • " Foo Bar Baz"

(但是字符串的其余部分没有设置自定义字体).

所以我的问题是:有没有办法指定一个字体用作默认的应用程序范围,但仍然可以使用属性字符串部分覆盖它?

此外,如果有人可以向我解释为什么这不起作用我会很感激.

小智 14

在设置属性字符串之前将font和textColor设置为nil.


bra*_*ipt 11

您不能混合和匹配属性文本和纯文本; 这就是删除setFont方法的原因- 因为当你使用它时,它会假定一个明文UILabel.

NSString *string = @"Foo Bar Baz";
UIFont *boldFont = [UIFont fontWithName:kMyBoldFontName size:15.0]; 
// Define your regular font
UIFont *regularFont = [UIFont fontWithName:kMyFontName size:15.0];
NSMutableAttributedString *attrString = [[NSMutableAttributedString alloc] initWithString:string];
// And before you set the bold range, set your attributed string (the whole range!) to the new attributed font name
[attrString setAttributes:@{ NSFontAttributeName: regularFont } range:NSMakeRange(0, string.length - 1)];
[attrString setAttributes:@{ NSFontAttributeName: boldFont } range:NSMakeRange(0, 3)];
self.myLabel.attributedText = attrString;
Run Code Online (Sandbox Code Playgroud)