0

在协议的文档中NSDraggingDestination,它说:

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

然后是九种方法。但我只实现了这九种方法中的三种(在我的NSViewdraggingEntered: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
4

1 回答 1

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 提供的文档的措辞具有误导性,您应该将其解释为“如果您想处理这些操作,您必须实施它们”。

于 2018-03-29T14:02:05.683 回答