【问题标题】:Where to get NSTextView dragged images reference在哪里获得 NSTextView 拖动图像参考
【发布时间】:2015-04-09 09:37:54
【问题描述】:

我有一个带有setImportGraphics(true) 的 NSTextView,我可以将图像拖到那里,它们会显示在界面中,但我不知道如何以编程方式获取(并存储)图像一旦被拖动。

如果我打电话给myNSTextView.string,我得到的只是图像周围的文字,但图像似乎不存在。

我是否必须实现一些有关拖放的方法来管理这种情况?

【问题讨论】:

    标签: cocoa nstextview


    【解决方案1】:

    我不知道如何在图像被拖动后以编程方式获取(并存储它)。

    丢弃的图像作为 NSTextAttachment 添加到 NSTextStorage。因此,为了访问丢弃的图像,您应该遍历 textStorage 的内容并检查符合图像文件的附件。

    我是否必须实现一些有关拖放的方法来管理这种情况

    您当然可以通过扩展 NSTextView 并覆盖 - (void)performDragOperation:(id<NSDraggingOperation>)sender 方法来处理删除的文件,如果您想这样做,我建议您阅读 Apple 的 Drag and Drop Programming Topics 文档。

    因为我不喜欢子类化,所以我对这个问题的回答使用 NSAttributedString 类别来返回附加图像的 NSArray。可以用下面的代码解决:

    #import "NSAttributedString+AttachedImages.h"
    
    @implementation NSAttributedString (AttachedImages)
    
    
    - (NSArray *)images
    {
        NSMutableArray *images = [NSMutableArray array];
        NSRange effectiveRange = NSMakeRange(0, 0);
    
        NSTextAttachment *attachment;
        CFStringRef extension;
        CFStringRef fileUTI;
    
        while (NSMaxRange(effectiveRange) < self.length) {
            attachment = [self attribute:NSAttachmentAttributeName atIndex:NSMaxRange(effectiveRange) effectiveRange:&effectiveRange];
    
            if (attachment) {
                extension = (__bridge CFStringRef) attachment.fileWrapper.preferredFilename.pathExtension;
                fileUTI = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, extension, NULL);
                if (UTTypeConformsTo(fileUTI, kUTTypeImage)) {
                    NSImage *theImage = [[NSImage alloc] initWithData:attachment.fileWrapper.regularFileContents];
                    [theImage setName:attachment.fileWrapper.preferredFilename];
    
                    [images addObject:theImage];
                }
            }
        }
    
        return images.copy;
    }
    
    @end
    

    如果你使用 GIT,你可以从我的Github repository 克隆代码。

    希望对你有帮助

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-04-11
      • 2015-02-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-31
      • 2013-08-17
      相关资源
      最近更新 更多