Rasmus Styrk
Rasmus Styrk

Reputation: 1346

NSTextField - make selected text bold, italic or underline?

I have an NSTextField where the user can write text. I would like to be able to make 3 buttons: bold, italic and underline; these buttons should change the user selection in the textfield to either bold, italic or underline.

Can anyone give me a pointer on how to do this?

Upvotes: 3

Views: 9391

Answers (2)

diciu
diciu

Reputation: 29333

Assuming your NSTextfield * is textField, the code below underlines the selection:

NSMutableAttributedString * as = [[[textField attributedStringValue] mutableCopy] autorelease];
[as beginEditing];
[as addAttribute:NSUnderlineStyleAttributeName
           value:[NSNumber numberWithInt:NSUnderlineStyleSingle]
           range:[[[textField window] fieldEditor:YES forObject:textField] selectedRange]];

[as endEditing];
[textField setAttributedStringValue:as];

Upvotes: 2

sidyll
sidyll

Reputation: 59287

The first thing is to enable rich text support, and you can do it either in Interface Builder by checking the "Rich Text" option in the inspector or by code using setAllowsEditingTextAttributes:.

Then it's all about NSAttributedStrings.

The big problem though is that looks like you need to apply changes to the selected text. This is not possible with NSTextFields. Only with NSTextViews.

If you can change it, go ahead and it will make things easier. However, if you do need to stick with NSTextField you may want to access the field editor. Each window has one associated, and it's what process the text behind the scenes.

NSTextView *editor = (NSTextView *)[window fieldEditor:YES forObject:myTextField]

Then you can call NSTextView's method setSelectedTextAttributes: happily.

Read more about the field editor here at Apple and in CocoaDev

Upvotes: 7

Related Questions