[英]NSAttributedString: Setting FontAttributes doesn't change font
我正在嘗試更改NSAttributedString上的字體。
我有一個遍歷每個字符的方法,並為該字符創建一個新的NSFontAttribute字典。 最后,該字符串保持不變。 為了演示,這是我如何設置字符串:
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}];
這將為整個字符串生成以下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本身仍然保持不變。 它仍然是默認字體。 如何獲得它以反映我對其屬性所做的更改?
解決方法如下:
1: UIFontDescriptor
的文檔定義了密鑰: UIFontDescriptorNameAttribute
作為NSString
實例。
2: NSAttributedString
的文檔定義了鍵: NSFontAttributeName
作為UIFont
實例。
因此獲得fontAttributes
從字典UIFontDescriptor
用該方法初始化: (UIFontDescriptor *)fontDescriptorWithName:(NSString *)fontName size:(CGFloat)size
只設置鍵UIFontDescriptorNameAttribute
和UIFontDescriptorSizeAttribute
。 但是,如果您希望實際修改NSAttributedString的字體,則需要應用帶有保存到鍵NSFontAttributeName
的UIFont實例的屬性。
這就是混亂的源頭。 但是,應該指出的是,你可以真正獲得UIFontDescriptorNameAttribute
從與鍵UIFontDescriptor實例的fontAttributes字典NSFontAttributeName
。 這也可能令人困惑。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.