gpt4 book ai didi

macos - NSCollectionView 拖放示例

转载 作者:行者123 更新时间:2023-12-03 16:06:23 27 4
gpt4 key购买 nike

我正在尝试在 NSCollectionView 中实现拖放,这将允许重新排列 View 中的单元格。我已经设置了委托(delegate)并实现了以下方法:

-(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

最佳答案

您只实现了委托(delegate)方法,但某些方法没有逻辑。例如,要拖动集合项,我将添加以下逻辑:

-(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;
}

您还需要将 Collection View 注册为awakefromnib中的拖动类型

[_myCollectionView registerForDraggedTypes:@[@"my_drag_type_id"]];

并确保您已将 Collection View 设置为可选择。

关于macos - NSCollectionView 拖放示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23286400/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com