NSAttributedString:设置FontAttributes不会改变字体

我正在尝试更改NSAttributedString上的字体。

我有一个迭代每个字符的方法,并为该字符创build一个新的NSFontAttribute字典。 但是,最后,string保持不变。 为了演示,这里是我如何设置string:

UIFontDescriptor *fontDescriptor = [UIFontDescriptor fontDescriptorWithName:@"Avenir-Book" size:14.0f]; NSDictionary *fontAttributes = [fontDescriptor fontAttributes]; [fontAttributes setValue:[NSString stringWithFormat:@"%u",[fontDescriptor symbolicTraits]] forKey:UIFontSymbolicTrait]; [mutableAttributedString setAttributes:fontAttributes range:(NSRange){0,length}]; 

这将为整个string生成以下NSFontAttribute字典:

 Font Attributes: { NSCTFontSymbolicTrait = 2147483648; NSFontNameAttribute = "Avenir-Book"; NSFontSizeAttribute = 14; } 

我通过并修改每个字符的FontAttribute来添加粗体或斜体,如下所示:

 for (int i = (int)range.location; i < (range.location + range.length); i++){ /* Extract Font Attributes */ NSDictionary *extractedAttributes = [[mutableAttributedString attributesAtIndex:i effectiveRange:NULL]mutableCopy]; /* Determine New Trait */ uint newTrait = ((uint)[[extractedAttributes valueForKey:UIFontSymbolicTrait]longLongValue] | [self symbolicTraitForMarkdownType:markdown]); // (markDown is a mask) /* Set New Trait */ [extractedAttributes setValue:[NSString stringWithFormat:@"%u",newTrait] forKey:UIFontSymbolicTrait]; /* Create New Font Descriptor */ UIFontDescriptor *newDescriptor = [UIFontDescriptor fontDescriptorWithFontAttributes:extractedAttributes]; newDescriptor = [newDescriptor fontDescriptorWithSymbolicTraits:newTrait]; /* Apply Font Descriptor */ [mutableAttributedString setAttributes:[newDescriptor fontAttributes] range:(NSRange){i,1}]; } 

这会产生许多不同的FontAttributes:

 Index 1: { NSCTFontSymbolicTrait = 2147483650; NSFontNameAttribute = "Avenir-Black"; NSFontSizeAttribute = 14; } Index 2: { NSCTFontSymbolicTrait = 2147483651; NSFontNameAttribute = "Avenir-BlackOblique"; NSFontSizeAttribute = 14; } 

但是,NSAttributedString本身保持完全不变。 它仍然是默认的字体。 我如何能够反映我正在对其属性所做的更改?

这是解决scheme:

1: UIFontDescriptor的文档将键: UIFontDescriptor定义为一个NSString实例。

2: NSAttributedString的文档将键: NSFontAttributeName定义为UIFont实例。

因此,从UIFontDescriptor获取fontAttributes字典时,将使用以下方法进行初始化: (UIFontDescriptor *)fontDescriptorWithName:(NSString *)fontName size:(CGFloat)size将只设置UIFontDescriptorNameAttributeUIFontDescriptorSizeAttribute 。 如果你希望实际修改一个NSAttributedString的字体,那么你需要应用保存在密钥NSFontAttributeName的UIFont实例的属性。

这是混乱的来源。 但是,应该注意的是,实际上您可以从UIFontDescriptor实例的fontAttributes字典中使用NSFontAttributeName关键字NSFontAttributeName 。 这也可能令人困惑。