Search code examples
iosnsattributedstring

How to selectively italicize text when using +[UIFont preferredFontForTextStyle:xxx]?


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.


Solution

  • // 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 };