NSDraggingDestination协议中必须使用哪些方法?

时间:2018-03-29 09:21:21

标签: macos drag-and-drop protocols nsdraggingdestination

In the Docs of the protocol NSDraggingDestination,它说:

  

目标对象(或接收者)的一组方法   拖动的图像必须实现。

然后遵循九种方法。但我只实施了这9种方法中的3种(在我的NSView中):draggingEntered:prepareForDragOperation:performDragOperation:

它编译并运行时没有警告或崩溃。文档并没有说某些方法是强制性的,而其他方法是可选的,那么它是如何工作的呢?

#import "Common.h"

@interface StageView : NSView <NSDraggingDestination>

@end

#import "StageView.h"

@implementation StageView

-(void)awakeFromNib {
    // we want pasteboard to hold a single URL (See Drag and Drop Programming Topics)
    NSLog(@"--registerForDraggedTypes");
    [self registerForDraggedTypes:@[NSURLPboardType]];
}


#pragma mark - DragAndDrop

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

-(BOOL)prepareForDragOperation:(id <NSDraggingInfo>)sender {
    NSLog(@"--prepareForDragOperation");
    //check to see if we can accept the data
    return YES;
}

// method that should handle the drop data
-(BOOL)performDragOperation:(id <NSDraggingInfo>)sender {
    NSLog(@"--performDragOperation");
    NSInteger numFiles = sender.numberOfValidItemsForDrop;
    CGPoint loc = sender.draggingLocation;
    NSURL *fileURL = [NSURL URLFromPasteboard: [sender draggingPasteboard]];
    NSString *ext = [fileURL pathExtension];

    if ([ext isEqualToString:@"mov"] && numFiles == 1) {
        [self handleVideo:loc url:fileURL];
        return YES;
    }

    return NO;
}


#pragma mark - Handle Video

-(void)handleVideo:(CGPoint)loc url:(NSURL *)fileURL {
    NSLog(@"--handleVideo");
    // ...
}

@end

1 个答案:

答案 0 :(得分:1)

如果你看一下实现,你会发现,事实上,所有方法都是可选的:

public protocol NSDraggingDestination : NSObjectProtocol {
    optional public func draggingEntered(_ sender: NSDraggingInfo) -> NSDragOperation

    optional public func draggingUpdated(_ sender: NSDraggingInfo) -> NSDragOperation

    optional public func draggingExited(_ sender: NSDraggingInfo?)

    optional public func prepareForDragOperation(_ sender: NSDraggingInfo) -> Bool

    optional public func performDragOperation(_ sender: NSDraggingInfo) -> Bool

    optional public func concludeDragOperation(_ sender: NSDraggingInfo?)

    optional public func draggingEnded(_ sender: NSDraggingInfo)

    optional public func wantsPeriodicDraggingUpdates() -> Bool

    optional public func updateDraggingItemsForDrag(_ sender: NSDraggingInfo?)
}

Apple提供的文档的措辞具有误导性,您应该将其解释为&#34;如果您想要处理这些操作,则必须实施它们。#/ p>