views:

250

answers:

2

Hey ho!
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

Thanks for your help!

+5  A: 

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.

Joshua Nozzi
If you're trying to wrap your head around the text system, you could do worse than start with this video of Aaron Hillegass talking about it: http://vimeo.com/4793853
James Williams
A simple code example would be great! :)
papr
It would, wouldn't it? :-) Unfortunately, it's not something that can be reduced to a StackOverflow-friendly length. There are examples floating around - try cocoadev.com and the usual friendly search engine. Keyword tips: NSLayoutManager, glyph range, nstextview drawBackgroundInRect: ...
Joshua Nozzi
Well ... let me rephrase that: it could probably be boiled down to the basics and be "short enough", but a fully-functional example is much better in this case. This isn't "light" material.
Joshua Nozzi
Thank you very much! :)
papr
A: 

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

Mike Abdullah
That does take care of the need to find the rects of the given range and custom drawing, but it seems a bit heavy to me. It also takes a little more effort to assign attributes (markup in this case) to desired ranges if you use custom attributes. Depending on the OP's goals, "what's best" could go either way, but there are plenty of disadvantages on either side.
Joshua Nozzi
(Ran out of room.) Assigning a span for a custom attribute is relatively easy, but multiple types of custom attribute now requires differentiation of span classes, etc. That's an extra layer. Additionally, it takes more effort (IMO) to locate and manipulate this markup in the doc versus the Cocoa text system.
Joshua Nozzi