簡體   English   中英

NSAttributedString:設置FontAttributes不會更改字體

[英]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只設置鍵UIFontDescriptorNameAttributeUIFontDescriptorSizeAttribute 但是,如果您希望實際修改NSAttributedString的字體,則需要應用帶有保存到鍵NSFontAttributeName的UIFont實例的屬性。

這就是混亂的源頭。 但是,應該指出的是,你可以真正獲得UIFontDescriptorNameAttribute從與鍵UIFontDescriptor實例的fontAttributes字典NSFontAttributeName 這也可能令人困惑。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM