我有一个NSTextView与setImportGraphics(true)
,我可以在那里拖动图像,它们出现在界面中,但我不知道如何以编程方式获取图像(并存储它)一旦被拖动。从哪里获得NSTextView拖动图像参考
如果我打电话myNSTextView.string
我所得到的只是图像周围的文字,但图像似乎并不存在。
我是否必须实施一些有关拖放的方法来管理这种情况?
我有一个NSTextView与setImportGraphics(true)
,我可以在那里拖动图像,它们出现在界面中,但我不知道如何以编程方式获取图像(并存储它)一旦被拖动。从哪里获得NSTextView拖动图像参考
如果我打电话myNSTextView.string
我所得到的只是图像周围的文字,但图像似乎并不存在。
我是否必须实施一些有关拖放的方法来管理这种情况?
我不知道如何以编程方式获取图像(并存储它),一旦它被拖动。
删除的图像作为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克隆代码。我希望它有帮助