0

I'm trying to create a custom “Change font” NSPopupButton for a Mac App (not an iOS App). I can detect a change in font selection:

long fontItemIndex = [fontPopup indexOfSelectedItem];
NSMenuItem *fontItem = [fontPopup itemAtIndex:(int)selectedFontItemIndex];
NSString *fontName = [selectedFontItem title];

Given this NSString of a font name, I cannot seem to find out how to actually change the selected text in my NSTextView textView to this new font.

I'm simply dazzled by the official documentation: it seems convertFont:toFamily: is what I need. When I do this:

NSFont *font = [NSFont fontWithName:fontName size:12.0];
[textView setFont:font];

It sets all text in the text view, not just the selected text. But when I do this:

NSFontManager *fontManager = [NSFontManager sharedFontManager];
[fontManager convertFont:[fontManager selectedFont] toFamily:fontName];

it doesn't do a thing. What am I missing?

NSGod
  • 22,699
  • 3
  • 58
  • 66
Joeri van Veen
  • 202
  • 1
  • 2
  • 9

3 Answers3

4

Inside a NSTextView is a NSTextStorage (a subclass of NSAttributedString) and you’ll have to modify the attribute named NSFontAttributeName.

First get the range where you want to change the font attribute:

NSRange selection = textView.selectedRange;

Now add the font attribute to the selection:

NSFont *font = [NSFont fontWithName:fontName size:12.0f];
[self.textView.textStorage addAttributes:@{NSFontAttributeName: font}
  range:selection];

Depending on the contents of your NSPopUpButton it should be enough to call fontWithName:size: with title as the font name to get the just selected font. But if the method you already do doesn’t work, you’ll probably have to get a specific font from the font family name. availableMembersOfFontFamily: on NSFontManager will give you a list of all available fonts. You can use one of them to initialize a specific font.

Rafael Bugajewski
  • 1,702
  • 3
  • 22
  • 37
0

Take a look at the setFont:range: method on NSText, the superclass of NSTextView.

(The ranges, of course, come from the selectedRanges property on NSTextView.)

Jim Puls
  • 79,175
  • 10
  • 73
  • 78
0

This was all I needed to change all the text in my textview.

[textview setFont:[NSFont fontWithName:@"Courier" size:14]];
Mountain Man
  • 252
  • 2
  • 10