Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSTextView with tokens

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

like image 494
gcstr Avatar asked Sep 21 '09 20:09

gcstr


2 Answers

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.

like image 119
Rob Keniger Avatar answered Oct 21 '22 03:10

Rob Keniger


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.

like image 29
heiko harrison Avatar answered Oct 21 '22 03:10

heiko harrison