Token text field like in Numbers

appkit, cocoa, nstextfield, nstokenfield, objective-c

Solution

I don't think there is a alternative control available for `NSTokenField` (well, I could not find one either a couple of weeks ago).

A possible option might be to follow the solution presented in Apple's sample project LayoutManagerDemo. This shows a subclass of `NSTextView` capable of detecting mouse movement over the text. Install and run the demo to get the basic idea.

The sample uses `NSLayoutManager` to detect mouse movement however the code could probably be adapted to detect specific character sequences in the text, like the tokens in your text field. Once you have the tokens and their location from `NSLocationManager`, you can insert your own representation based on the characteristics of your token. A possible solution could be to use `NSTextAttachmentCell` which will become a glyph inside your text. The benefit of using `NSTextAttachmentCell` is that it's treated as a glyph by Cocoa's text system (you can select it, it follows formatting etc.). By implementing `drawWithFrame:inView:` you can add the various visible attributes of each token.

Problem

I'd like to have a text field like the expression editor text field in Numbers: It's very similar to `NSTokenField`, but `NSTokenField` only supports a delimiter separated list of tokens, like the "To:" field in Mail.app. I have to embed these tokens into the text at specific locations, but otherwise have them work exactly like `NSTokenField` (backspace deletes a token, you can drag them around etc.). Is there any 1st or 3rd party control that does something like this? I didn't find anything. If not, how would you recommend implementing it? Use Core Text and reinvent the wheel (implement `NSTextField` with better token support)? Or is there a better solution?

Original source