How can I add tokens, like NSTokenField
, to a NStextView
?
Asked
Active
Viewed 2,993 times
12
2 Answers
11
This is actually a little complicated. You will need to create a custom NSTextAttachment
for each "token" and insert it into the NSTextStorage
for your NSTextView
.
There is a great post by David Sinclair at Dejal Systems which explains how to do it.

DD_
- 7,230
- 11
- 38
- 59

Rob Keniger
- 45,830
- 6
- 101
- 134
-
1Thanks man. I didn't know where to start looking for it. It's a great beginning. – gcstr Sep 21 '09 at 22:24
-
1Wow, the article was written all the way back in 2007... Does it apply to the newer iOS 7 TextKit implementation of the TextView? – fatuhoku Jun 24 '14 at 10:26
-
The article was written for MacOS. What's the latest on iOS? – fatuhoku Jun 24 '14 at 10:28
4
I figured out an easy approach that uses a custom cell class for tokens:
- Write a cell class that inherits
NSTextAttachmentCell
and reimplement
- (void)drawWithFrame:(NSRect)cellFrame inView:(NSView *)controlView
That will be the class that represents the tokens in yourNSTextView
. - To insert a token follow these steps:
- Create an instance of
NSTextAttachment
- Set the cell of the attachment to an instance of your token cell class.
- Create an attributed string with that attachment.
- Insert the attributed string into the text view.
- Create an instance of
A method that inserts a token into the text view might look like this:
- (void)insertAttachmentCell:(NSTextAttachmentCell *)cell toTextView:(NSTextView *)textView
{
NSTextAttachment *attachment = [NSTextAttachment new];
[attachment setAttachmentCell:cell];
[textView insertText:[NSAttributedString attributedStringWithAttachment:attachment]];
}
This approach is more appropriate for tokens than the one by David Sinclair. There is no need to use file wrappers since we want to display dynamic contents (tokens) rather than static images.
A look at David's concepts might be useful though. He depicts a good approach to implement the drag and drop resp. copy paste functionalities.

DD_
- 7,230
- 11
- 38
- 59

heiko harrison
- 307
- 3
- 8