NSCollectionView Drag Drop示例

use*_*975 7 macos cocoa

我正在尝试实现拖放,NSCollectionView这将允许重新排列视图中的单元格.我已设置委托并在以下方法中实现:

-(BOOL)collectionView:(NSCollectionView *)collectionView writeItemsAtIndexes:(NSIndexSet *)indexes toPasteboard:(NSPasteboard *)pasteboard {
    NSLog(@"Write Items at indexes : %@", indexes);
    return YES;
}

- (BOOL)collectionView:(NSCollectionView *)collectionView canDragItemsAtIndexes:(NSIndexSet *)indexes withEvent:(NSEvent *)event {
    NSLog(@"Can Drag");
    return YES;
}

- (BOOL)collectionView:(NSCollectionView *)collectionView acceptDrop:(id<NSDraggingInfo>)draggingInfo index:(NSInteger)index dropOperation:(NSCollectionViewDropOperation)dropOperation {
    NSLog(@"Accept Drop");
    return YES;
}

-(NSDragOperation)collectionView:(NSCollectionView *)collectionView validateDrop:(id<NSDraggingInfo>)draggingInfo proposedIndex:(NSInteger *)proposedDropIndex dropOperation:(NSCollectionViewDropOperation *)proposedDropOperation {
    NSLog(@"Validate Drop");
    return NSDragOperationMove;
}
Run Code Online (Sandbox Code Playgroud)

我不确定如何进一步采取这一点.有了这个我可以看到,现在我可以拖动个别收集项目,但我怎么能做到Drop

Goo*_*33d 6

您只实现了委托方法,但某些方法中没有逻辑.例如,要拖动Collection Item,我会添加以下逻辑:

-(BOOL)collectionView:(NSCollectionView *)collectionView writeItemsAtIndexes:(NSIndexSet *)indexes toPasteboard:(NSPasteboard *)pasteboard {
    NSData *indexData = [NSKeyedArchiver archivedDataWithRootObject:indexes];
    [pasteboard setDraggedTypes:@["my_drag_type_id"]];
    [pasteboard setData:indexData forType"@"my_drag_type_id"];
    // Here we temporarily store the index of the Cell, 
    // being dragged to pasteboard.
    return YES;
}

- (BOOL)collectionView:(NSCollectionView *)collectionView acceptDrop:(id<NSDraggingInfo>)draggingInfo index:(NSInteger)index dropOperation:(NSCollectionViewDropOperation)dropOperation {
    NSPasteboard *pBoard = [draggingInfo draggingPasteboard];
    NSData *indexData = [pBoard dataForType:@"my_drag_type_id"];
    NSIndexSet *indexes = [NSKeyedUnarchiver unarchiveObjectWithData:indexData];
    NSInteger draggedCell = [indexes firstIndex];
    // Now we know the Original Index (draggedCell) and the 
    // index of destination (index). Simply swap them in the collection view array.
    return YES;
}
Run Code Online (Sandbox Code Playgroud)

您还需要注册集合视图以在awakefromnib中拖动类型

[_myCollectionView registerForDraggedTypes:@[KL_DRAG_TYPE]];
Run Code Online (Sandbox Code Playgroud)

并确保您已将集合视图设置为可选.