gpt4 book ai didi

cocoa - 如何允许通过在 NSTableView 中拖动行来移动和复制?

转载 作者:行者123 更新时间:2023-12-03 16:35:21 28 4
gpt4 key购买 nike

我有一个 NSTableView,我希望能够拖放行来移动它们,并在按住 Option 的同时拖放行(按照 Apple's documentation )来复制它们。

我的 View Controller 中有以下代码,它也是 TableView 的dataSource

- (void)awakeFromNib {
[self.tableView registerForDraggedTypes:@[kRowIndexesPasteboardType]];
}

- (BOOL)tableView:(NSTableView *)tableView writeRowsWithIndexes:(NSIndexSet *)rowIndexes toPasteboard:(NSPasteboard *)pasteboard {
NSData *data = [NSKeyedArchiver archivedDataWithRootObject:rowIndexes];
[pasteboard declareTypes:@[kRowIndexesPasteboardType] owner:self];
[pasteboard setData:data forType:kRowIndexesPasteboardType];
return YES;
}

- (NSDragOperation)tableView:(NSTableView *)tableView validateDrop:(id <NSDraggingInfo>)info proposedRow:(NSInteger)row proposedDropOperation:(NSTableViewDropOperation)dropOperation {
// Only allow dropping above/below.
return dropOperation == NSTableViewDropAbove ? (NSDragOperationMove|NSDragOperationCopy) : NSDragOperationNone;
}

- (BOOL)tableView:(NSTableView *)tableView acceptDrop:(id <NSDraggingInfo>)info row:(NSInteger)row dropOperation:(NSTableViewDropOperation)dropOperation {
if (dropOperation == NSTableViewDropAbove) {
NSPasteboard* pasteboard = [info draggingPasteboard];
NSData* rowData = [pasteboard dataForType:kRowIndexesPasteboardType];
NSIndexSet* rowIndexes = [NSKeyedUnarchiver unarchiveObjectWithData:rowData];

BOOL copy = ???;
if (copy) {
// Copy items at rowIndexes to row.
} else {
// Move items at rowIndexes to row.
}
return YES;
}
return NO;
}
  1. 如何使默认的拖动操作为移动,并且仅在按住 Option 键时才进行复制?目前它默认立即复制。
  2. tableView:acceptDrop:row:dropOperation: 中,如何判断该操作是复制操作还是删除操作?

最佳答案

this discussion 中所述当没有按住修饰键时,draggingSourceOperationMask 的值将为 NSDragOperationEvery(除非更改):

When it comes back to your table as a drop validation without any modification by the user (no option key down) then any of the original options need to be considered as being possible. Your validation should then pick the operation (out of the source allowed options) that you will do based on what makes sense for the target of the drop.

这意味着当按住Option键时,以下方法将返回NSDragOperationCopy,否则返回NSDragOperationMove:

- (NSDragOperation)tableView:(NSTableView *)tableView validateDrop:(id <NSDraggingInfo>)info proposedRow:(NSInteger)row proposedDropOperation:(NSTableViewDropOperation)dropOperation {
// Allow moving or copying the rows.
NSDragOperation moveOrCopy = (info.draggingSourceOperationMask == NSDragOperationCopy ? NSDragOperationCopy : NSDragOperationMove);
// Only allow dropping above/below.
return dropOperation == NSTableViewDropAbove ? moveOrCopy : NSDragOperationNone;
}

同样,可以以类似的方式在 tableView:acceptDrop:row:dropOperation: 中检查操作。

关于cocoa - 如何允许通过在 NSTableView 中拖动行来移动和复制?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32408338/

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