12

How can I add tokens, like NSTokenField, to a NStextView?

DD_
  • 7,230
  • 11
  • 38
  • 59
gcstr
  • 1,466
  • 1
  • 21
  • 45

2 Answers2

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
4

I figured out an easy approach that uses a custom cell class for tokens:

  1. 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 your NSTextView.
  2. To insert a token follow these steps:
    1. Create an instance of NSTextAttachment
    2. Set the cell of the attachment to an instance of your token cell class.
    3. Create an attributed string with that attachment.
    4. Insert the attributed string into the text view.

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