简体   繁体   English

带令牌的NSTextView

[英]NSTextView with tokens

如何将标记(如NSTokenField添加到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 . 您需要为每个“令牌”创建一个自定义NSTextAttachment ,并将其插入NSTextStorage以用于您的NSTextView

There is a great post by David Sinclair at Dejal Systems which explains how to do it. Dejal Systems的David Sinclair发表了一篇很棒的文章 ,解释了如何做到这一点。

I figured out an easy approach that uses a custom cell class for tokens: 我想出了一个简单的方法,它使用自定义单元格类来标记:

  1. Write a cell class that inherits NSTextAttachmentCell and reimplement 编写一个继承NSTextAttachmentCell并重新实现的单元类
    - (void)drawWithFrame:(NSRect)cellFrame inView:(NSView *)controlView
    That will be the class that represents the tokens in your NSTextView . 这将是代表NSTextView令牌的类。
  2. To insert a token follow these steps: 要插入令牌,请按以下步骤操作:
    1. Create an instance of NSTextAttachment 创建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 . 这种方法比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. 复制粘贴功能。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM