我试图在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;
}我不知道如何进一步发展。有了这个,我可以看到,现在我可以拖动单个集合项,但是如何使Drop?
发布于 2014-04-30 17:30:25
您只实现了委托方法,但是有些方法没有逻辑。例如,要拖动一个集合项,我将添加以下逻辑:
-(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;
}您还需要注册集合视图,以便将awakefromnib中的类型拖动为
[_myCollectionView registerForDraggedTypes:@[@"my_drag_type_id"]];并确保将集合视图设置为可选视图。
发布于 2017-02-19 10:42:29
除了上面GoodSp33d提到的内容之外,您还缺少了接受drops所需的validate委托函数。在Swift中,这是:
func collectionView(_ collectionView: NSCollectionView, validateDrop draggingInfo: NSDraggingInfo, proposedIndexPath proposedDropIndexPath: AutoreleasingUnsafeMutablePointer<NSIndexPath>, dropOperation proposedDropOperation: UnsafeMutablePointer<NSCollectionViewDropOperation>) -> NSDragOperation注意返回值NSDragOperation。此方法应包含准确确定尝试执行何种拖动操作并返回此值的代码。返回错误的东西可能会导致一些相当恼人的错误。
进一步注意,为了支持这种操作,您使用的集合视图布局类也必须支持拖放。流布局应该是开箱即用的,但是如果您使用的是自定义布局,则可能需要调整它以支持拖放,以便集合视图能够检测有效的拖放目标并为它们确定合适的索引路径。
https://stackoverflow.com/questions/23286400
复制相似问题