-->

Cannot get drag and drop to work onto NSCollection

2019-03-03 14:17发布

问题:

There is probably a simple mistake that I'm making, but I simply cannot get dropping of files onto an NSCollectionView to work even in the most basic way.

In a test project, I have an NSCollectionView on a window, and the view controller is both its delegate and data source. I want to be able to drag files from the Finder onto this collection view.

From reading the docs, all I should have to do is:

Register for dragged type(s):

- (void)viewDidLoad {

    [super viewDidLoad];
    // Do any additional setup after loading the view.

    NSLog(@"Registering dragged types for collection view: %@", self.collectionView);
    [self.collectionView registerForDraggedTypes:@[NSFilenamesPboardType]];
    [self.collectionView setDraggingSourceOperationMask:NSDragOperationEvery forLocal:YES];
    [self.collectionView setDraggingSourceOperationMask:NSDragOperationEvery forLocal:NO];
}

And then implement these two methods:

-(NSDragOperation)collectionView:(NSCollectionView *)collectionView validateDrop:(id<NSDraggingInfo>)draggingInfo proposedIndex:(NSInteger *)proposedDropIndex dropOperation:(NSCollectionViewDropOperation *)proposedDropOperation {

    NSLog(@"Validate drop: %@", draggingInfo);

    return NSDragOperationMove;
}

-(BOOL)collectionView:(NSCollectionView *)collectionView acceptDrop:(id<NSDraggingInfo>)draggingInfo index:(NSInteger)index dropOperation:(NSCollectionViewDropOperation)dropOperation {

    NSLog(@"Accept drop: %@", draggingInfo);

    return YES;
}

But none of the two methods is ever called, when I try to drag an item onto the collection view, which makes me think that the registerForDraggedTypes: call is not working as expected.

What can be the issue here? What else do I have to look into?

回答1:

From OS X 10.11 the NSCollectionViewDelegate methods take an index path instead of an index. For instance in

-(NSDragOperation)collectionView:(NSCollectionView *)collectionView validateDrop:(id<NSDraggingInfo>)draggingInfo proposedIndex:(NSInteger *)proposedDropIndex dropOperation:(NSCollectionViewDropOperation *)proposedDropOperation

the proposedIndex: parameter is replaced by proposedIndexPath:

- (NSDragOperation)collectionView:(NSCollectionView *)collectionView validateDrop:(id <NSDraggingInfo>)draggingInfo proposedIndexPath:(NSIndexPath * __nonnull * __nonnull)proposedDropIndexPath dropOperation:(NSCollectionViewDropOperation *)proposedDropOperation