Question

If you wanted to implement a highlighting for specific substrings in a NSTextField like on the screenshot (Tweetie.app) how would you do it? :) Tweetie Link Highlighting http://qkpic.com/88c61

Thanks for your help!

Was it helpful?

Solution

For an NSTextField, note that it's an NSTextFieldCell that does the drawing. You'll want to override -drawInteriorWithFrame:inView: and do the string drawing yourself. The challenge will be finding the rectangles (more than one if the range is wrapped) in which your substring is drawn. You'll end up having to use NSLayoutManager and an NSTextStorage container.

Best to use an NSTextView. The associated NSLayoutManager and NSTextStorage components are already pre-assembled and you get a lot of other functionality for free. Most importantly, there's a convenient -[NSTextView drawViewBackgroundInRect:] method so you don't have to subclass anything. You just ask the text view for its layout manager and text storage, then ask it for the rectangles for the given range. See the Text System Overview and linked documents for more details.

To find the interesting substrings efficiently, you might use custom attributes (or the built-in ones such as NSLinkAttributeName) for your interesting ranges.

OTHER TIPS

An alternative to consider is an editable WebView where you can build the custom attributes with CSS.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top