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?
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 withNSTextViews.If you can change it, go ahead and it will make things easier. However, if you do need to stick with
NSTextFieldyou may want to access the field editor. Each window has one associated, and it’s what process the text behind the scenes.Then you can call NSTextView’s method
setSelectedTextAttributes:happily.Read more about the field editor here at Apple and in CocoaDev