如何在使用+ [UIFont preferredFontForTextStyle:xxx]时选择性地斜体显示文本?

时间:2014-08-21 12:18:24

标签: ios nsattributedstring

我像这样创建一个NSMutableAttributedString

UIFont *font = [UIFont preferredFontForTextStyle:UIFontTextStyleBody];
NSDictionary *attributes = @{ NSFontAttributeName: font };
NSMutableAttributedString *attrStr = [[NSMutableAttributedString alloc] initWithString:str attributes:attributes];

现在我想通过以下方式 italicize 特定范围的attrStr:

- (void)setAttributes:(NSDictionary *)attrs range:(NSRange)range;

但由于我从未要求过特定的字体,所以我不确定我是怎么做的。

2 个答案:

答案 0 :(得分:3)

// Create the normal body style font    
UIFont *font = [UIFont preferredFontForTextStyle:UIFontTextStyleBody];

// Get the font's descriptor and add the italics trait
UIFontDescriptor *fontDesc = [font fontDescriptor];
fontDesc = [fontDesc fontDescriptorWithSymbolicTraits:UIFontDescriptorTraitItalic];

// Create the italicized font from the descriptor
UIFont *italicsFont = [UIFont fontWithDescriptor:fontDesc size:font.pointSize];

// Create the attributes dictionary that we'll use to italicize parts of our NSMutableAttributedString
NSDictionary *italicsAttributes = @{ NSFontAttributeName: italicsFont };

答案 1 :(得分:2)

使用RobertJoseph的答案来制作Swift 3扩展程序。

extension UIFont {

    class func preferredItalicFont(forTextStyle style: UIFontTextStyle) -> UIFont? {
        return UIFont.preferredFont(forTextStyle: style).italicisedVariant
    }

    var italicisedVariant: UIFont? {
        guard let italicDescriptor = fontDescriptor.withSymbolicTraits(.traitItalic) else { return nil }
        return UIFont(descriptor: italicDescriptor, size: pointSize)
    }

}