我有一個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克隆代碼。我希望它有幫助