4

I create an NSMutableAttributedString like this:

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

Now I'd like to italicize specific ranges of attrStr via something like:

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

but since I never asked for a specific font I'm not sure how I'd go about it.

RobertJoseph
  • 7,968
  • 12
  • 68
  • 113
  • http://stackoverflow.com/questions/25401742/apply-custom-font-to-attributed-string-which-converts-from-html-string#comment39621924_25401742 ? – Larme Aug 21 '14 at 12:35

2 Answers2

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 };
RobertJoseph
  • 7,968
  • 12
  • 68
  • 113
2

Used RobertJoseph's answer to make a Swift 3 extension.

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)
    }

}
Mark Bridges
  • 8,228
  • 4
  • 50
  • 65