-->

NSTextField - make selected text bold, italic or u

2020-06-23 07:50发布

问题:

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?

回答1:

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



回答2:

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];