带令牌的NSTextView

gcs*_*str 12 cocoa objective-c nstextview

我如何添加标记,就像NSTokenField,一个NStextView

Rob*_*ger 10

这实际上有点复杂.您需要NSTextAttachment为每个"令牌" 创建一个自定义,并将其插入到NSTextStorage您的NSTextView.

Dejal Systems的David Sinclair发表了一篇很棒的文章,解释了如何做到这一点.


小智 5

我找到了一种简单的方法,使用自定义单元类作为标记:

  1. NSTextAttachmentCell编写一个继承并重新实现的单元类
    - (void)drawWithFrame:(NSRect)cellFrame inView:(NSView *)controlView
    ,这将是代表您的NSTextView.
  2. 要插入令牌,请按照下列步骤操作:
    1. 创建一个实例NSTextAttachment
    2. 将附件的单元设置为令牌单元类的实例。
    3. 使用该附件创建属性字符串。
    4. 将属性字符串插入文本视图。

将标记插入文本视图的方法可能如下所示:

- (void)insertAttachmentCell:(NSTextAttachmentCell *)cell toTextView:(NSTextView *)textView
{
    NSTextAttachment *attachment = [NSTextAttachment new];
    [attachment setAttachmentCell:cell];
    [textView insertText:[NSAttributedString attributedStringWithAttachment:attachment]];
}
Run Code Online (Sandbox Code Playgroud)

这种方法比David Sinclair的方法更适合代币。不需要使用文件包装器,因为我们想要显示动态内容(令牌)而不是静态图像。
不过,了解一下大卫的概念可能会有用。他描述了一种实现拖放的好方法。复制粘贴功能。

  • 在 iOS 上怎么样,没有 NSTextAttachmentCell 类? (3认同)