2012-08-28 28 views
2

我想實現一些「簡單」拖放到我的Mac應用程序中的&。 我拖入一個視圖,並相應地在我的筆尖文件中輸入「MyView」。但是我沒有在我的控制檯中得到任何迴應(我試圖在任何協議方法觸發時記錄消息)在Cocoa中拖放(<NSDraggingDestination>)不起作用

我已經子類NSView像這樣:

@interface MyView : NSView <NSDraggingDestination>{ 
    NSImageView* imageView; 
} 

,並實現它是這樣的:

- (id)initWithFrame:(NSRect)frame 
{ 
    self = [super initWithFrame:frame]; 
    if (self) { 

     [self registerForDraggedTypes:[NSImage imagePasteboardTypes]]; 

     NSRect rect = NSMakeRect(150, 0, 400, 300); 
     imageView = [[NSImageView alloc] initWithFrame:rect]; 

     [imageView setImageScaling:NSScaleNone]; 
     [imageView setImage:[NSImage imageNamed:@"test.png"]]; 
     [self addSubview:imageView]; 



    } 

    return self; 
} 


- (NSDragOperation)draggingEntered:(id <NSDraggingInfo>)sender{ 
    NSLog(@"entered"); 
    return NSDragOperationCopy; 

} 

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

} 


- (void)draggingExited:(id <NSDraggingInfo>)sender{ 
    NSLog(@"exited"); 

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

} 

- (BOOL)performDragOperation:(id<NSDraggingInfo>)sender { 

    NSPasteboard *pboard = [sender draggingPasteboard]; 

    if ([[pboard types] containsObject:NSURLPboardType]) { 
     NSURL *fileURL = [NSURL URLFromPasteboard:pboard]; 
     NSLog(@"%@", fileURL); 
    } 
    return YES; 
} 

- (void)concludeDragOperation:(id <NSDraggingInfo>)sender{ 
    NSLog(@"conclude sth"); 


} 

- (void)draggingEnded:(id <NSDraggingInfo>)sender{ 
    NSLog(@"ended"); 


} 

- (BOOL)wantsPeriodicDraggingUpdates{ 
    NSLog(@"wants updates"); 

} 


- (void)updateDraggingItemsForDrag:(id <NSDraggingInfo>)sender NS_AVAILABLE_MAC(10_7){ 
} 

回答

11

如果有人仍然需要這一點,使用:

[self registerForDraggedTypes:[NSArray arrayWithObjects: 
         NSFilenamesPboardType, nil]]; 

代替:

[self registerForDraggedTypes: 
         [NSImage imagePasteboardTypes]]; // BAD: dropped image runs away, no draggingdestination protocol methods sent... 

解決了這個問題對我來說。我懷疑這是有效的,因爲我的XIB是針對osX 10.5的。 NSFilenamesPboardType表示10.5和之前的'標準數據'UTI,[NSImage imagePasteboardTypes]返回10.6和之後的標準數據UTI。

順便說一句,在- (BOOL)performDragOperation:(ID NSDraggingInfo)發送,你可以得到與取消了對文件的路徑:

NSArray *files = [pboard propertyListForType:NSFilenamesPboardType]; 

在這裏得到了解決:

http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/DragandDrop/Tasks/acceptingdrags.html#//apple_ref/doc/uid/20000993-BABHHIHC

+0

imagePasteboardTypes =僅限圖片內容 –