NSTextField - make selected text bold, italic or underline?

房东的猫 提交于 2019-12-21 05:45:17

问题


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


来源:https://stackoverflow.com/questions/4861756/nstextfield-make-selected-text-bold-italic-or-underline

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!