How to change only font size for the whole styled text in NSTextView

Indoor picture Indoor · Feb 11, 2010 · Viewed 8.3k times · Source

I need to set a text size (for example to 42) of the selected rich text which uses multiple fonts.

I imagine I can check attributes of each group of characters, modify the font size and set attributes back, but looking at the floating Font panel it seems like there should be a very easy and straightforward way to accomplish that. Do I miss something obvious?

Answer

Jonathan Mitchell picture Jonathan Mitchell · Jan 28, 2011

On 10.6 there is a convenient way to iterate over the attributes and increase the font size. This method can be added to an NSTextView category.

    - (IBAction)increaseFontSize:(id)sender
{
    NSTextStorage *textStorage = [self textStorage];
    [textStorage beginEditing];
    [textStorage enumerateAttributesInRange: NSMakeRange(0, [textStorage length])
                                     options: 0
                                  usingBlock: ^(NSDictionary *attributesDictionary,
                                                NSRange range,
                                                BOOL *stop)
     {
#pragma unused(stop)
         NSFont *font = [attributesDictionary objectForKey:NSFontAttributeName];
         if (font) {
             [textStorage removeAttribute:NSFontAttributeName range:range];
             font = [[NSFontManager sharedFontManager] convertFont:font toSize:[font pointSize] + 1];
             [textStorage addAttribute:NSFontAttributeName value:font range:range];
         }
     }];
    [textStorage endEditing];
    [self didChangeText];

}