How can I add tokens, like NSTokenField
, to a NStextView
?
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.
I figured out an easy approach that uses a custom cell class for tokens:
NSTextAttachmentCell
and reimplement- (void)drawWithFrame:(NSRect)cellFrame inView:(NSView *)controlView
NSTextView
.NSTextAttachment
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With