首页 文章

NSAttributedString:设置FontAttributes不会更改字体

提问于
浏览
0

我试图更改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 回答

  • 0

    这是解决方案:

    1: UIFontDescriptor 的文档定义了密钥: UIFontDescriptorNameAttribute 作为 NSString 实例,它是 .

    2: NSAttributedString 的文档定义了密钥: NSFontAttributeName 作为 UIFont 实例 .

    因此,从使用方法初始化的 UIFontDescriptor 获取 fontAttributes 字典: (UIFontDescriptor *)fontDescriptorWithName:(NSString *)fontName size:(CGFloat)size 将仅设置键 UIFontDescriptorNameAttributeUIFontDescriptorSizeAttribute . 但是,如果您希望实际修改NSAttributedString的字体,则需要将保存有UIFont实例的属性应用于键 NSFontAttributeName .

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

相关问题