在我的应用程序中,我有一个带有自定义 CollectionViewItem 的 NSCollectionView。它用于显示图像。我激活了“允许多重选择”选项,并且可以使用鼠标选择多个项目。
但是,对于 NSCollectionView,我还有一个右键单击时打开的 ContextMenu。但是,如果我单击某个项目,我的选择就会丢失。只有我点击的项目才会被标记。我不想要这样。我想打开上下文菜单并保留多个项目的选择。仅当我在两个项目之间单击而不是在一个项目上单击时,这才有效。
如何通过右键单击某个项目来阻止选择?
更新
上下文菜单是通过 Interface Builder 实现的。我将它拖到 ViewController 上,然后将其与 CollectionView 的菜单导出连接起来。
最佳答案
我还没有机会测试或完善这个 - 忙碌的一天,抱歉 - 但我认为你可以通过这种方式到达你要去的地方。设置 Collection View 委托(delegate),并添加 collectionView:shouldSelectItemsAtIndexPaths:
和/或 collectionView:shouldDeselectItemsAtIndexPaths:
方法(不过我不确定您是否需要这两个方法)看起来有可能)。然后添加一个例程来测试当前事件以查看是否是鼠标右键单击:
- (NSSet<NSIndexPath *> *)collectionView:(NSCollectionView *)collectionView shouldDeselectItemsAtIndexPaths:(NSSet<NSIndexPath *> *)indexPaths {
return ([self testForRightClick]) ? indexPaths : [NSSet set];
}
- (NSSet<NSIndexPath *> *)collectionView:(NSCollectionView *)collectionView shouldSelectItemsAtIndexPaths:(NSSet<NSIndexPath *> *)indexPaths {
return ([self testForRightClick]) ? indexPaths : [NSSet set];
}
- (BOOL)testForRightClick {
NSEvent * currentEvent;
currentEvent = [NSApp currentEvent];
return (currentEvent.type == NSEventTypeRightMouseDown ||
currentEvent.type == NSEventTypeRightMouseUp) ? NO : YES;
}
对于任何其他类型的事件,这会直接发送保存选择/取消选择请求的 NSSet,但如果该事件是鼠标右键向上/向下事件,它将返回一个空集,这应该阻止任何取消选择或新的选择。
关于swift - NSCollectionView : How to prevent right click selection?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57017772/