1

我在主xib(MainMenu.xib)中有一個小窗口,其中有一個NSImageView控件用於OS x應用程序。這個視圖控件有一個NSImageView子類,它應該接受用戶帶來的文件(拖拽拖放)。由於我沒有使用Objective-C開發Mac應用程序的經驗,所以我搜索了一下,查看了一些來自Apple的示例項目,並得到了一些想法。那麼,爲了簡短起見,我剛剛複製了代碼here。有用。好...以下是一個簡潔的版本。讀取多個拖拽的文件

- (NSDragOperation)draggingEntered:(id <NSDraggingInfo>)sender{ 
    return NSDragOperationCopy; 
} 

- (NSDragOperation)draggingUpdated:(id <NSDraggingInfo>)sender{ 
} 

- (void)draggingExited:(id <NSDraggingInfo>)sender{ 
} 

- (BOOL)prepareForDragOperation:(id <NSDraggingInfo>)sender{ 
    return YES; 
} 

- (BOOL)performDragOperation:(id<NSDraggingInfo>)sender { 
    NSPasteboard *pboard = [sender draggingPasteboard]; 
    if ([[pboard types] containsObject:NSURLPboardType]) { 
     NSURL *fileURL = [NSURL URLFromPasteboard:pboard]; 
     NSLog(@"Path: %@", [self convertPath:fileURL]); // <== That's just what I need 
    } 
    return YES; 
} 

- (NSString *)convertPath:(NSURL *)url { 
    return url.path; 
} 

現在,無論用戶拖放到投遞箱上的文件的數量如何,投遞箱一次只能獲取一個文件路徑。所以我想知道的是如何讓應用程序讀取用戶帶來的所有多個文件。

謝謝

回答

11

更改performDragOperation:方法是:

- (BOOL)performDragOperation:(id<NSDraggingInfo>)sender { 
    NSPasteboard *pboard = [sender draggingPasteboard]; 
    if ([[pboard types] containsObject:NSURLPboardType]) { 
     NSArray *urls = [pboard readObjectsForClasses:@[[NSURL class]] options:nil]; 
     NSLog(@"URLs are: %@", urls); 
    } 
    return YES; 
} 
+0

非常感謝你。有用。看來下面的話題也能幫助我。 http://stackoverflow.com/questions/1998158/how-do-i-handle-multiple-file-drag-drop-from-finder-in-mac-os-x-10-5?rq=1 – 2013-05-08 21:16:50

+0

這個答案是金色的。從紙板上接收多個NSURL時,我遇到了很大的麻煩。我一直只限於一個。這固定了它。 – 2013-05-22 21:39:44

2

雨燕風格:

override func performDragOperation(sender: NSDraggingInfo) -> Bool 
{ 
    if let board = sender.draggingPasteboard().propertyListForType(NSFilenamesPboardType) as? NSArray 
    {    
     for imagePath in board 
     { 
      if let path = imagePath as? String 
      { 
       println("path: \(path)") 
      } 
     }     
     return true    
    } 
    return false 
}