如何通过再次单击NSCollectionViewItem来取消选择它?
这是我用来选择和取消选择的代码:
func collectionView(collectionView: NSCollectionView, didSelectItemsAtIndexPaths indexPaths: Set<NSIndexPath>) {
print("selected")
guard let indexPath = indexPaths.first else {return}
print("selected 2")
guard let item = collectionView.itemAtIndexPath(indexPath) else {return}
print("selected 3")
(item as! CollectionViewItem).setHighlight(true)
}
func collectionView(collectionView: NSCollectionView, didDeselectItemsAtIndexPaths indexPaths: Set<NSIndexPath>) {
print("deselect")
guard let indexPath = indexPaths.first else {return}
print("deselect 2")
guard let item = collectionView.itemAtIndexPath(indexPath) else {return}
print("deselect 3")
(item as! CollectionViewItem).setHighlight(false)
}
/////////////////////
class CollectionViewItem: NSCollectionViewItem {
func setHighlight(selected: Bool) {
print("high")
view.layer?.borderWidth = selected ? 5.0 : 0.0
view.layer?.backgroundColor = selected ? NSColor.redColor().CGColor : NSColor(calibratedRed: 204.0/255, green: 207.0/255, blue: 1, alpha: 1).CGColor
}
}此代码在单击另一项时取消选择,但不在同一项被单击时取消选择。当相同的项目被点击时,我想删除。
发布于 2018-01-31 17:56:45
您可以通过观察项目的选中状态来实现这一点,当项目处于选中状态时,在项目的视图上安装NSClickGestureRecognizer,在取消选中项目时将其卸载。
将以下代码放在您的NSCollectionViewItem子类中的某个位置:
- (void)onClick:(NSGestureRecognizer *)sender {
if (self.selected) {
//here you can deselect this specific item, this just deselects all
[self.collectionView deselectAll:nil];
}
}
- (void)setSelected:(BOOL)selected {
[super setSelected:selected];
if (selected) {
[self installGestureRecognizer];
}
else {
[self uninstallGestureRecognizer];
}
}
- (void)installGestureRecognizer {
[self uninstallGestureRecognizer];
self.clickGestureRecognizer = [[NSClickGestureRecognizer alloc] initWithTarget:self
action:@selector(onClick:)];
[self.view addGestureRecognizer:self.clickGestureRecognizer];
}
- (void)uninstallGestureRecognizer {
[self.view removeGestureRecognizer:self.clickGestureRecognizer];
self.clickGestureRecognizer = nil;
}发布于 2016-08-02 18:02:36
一个简单的技巧是使用CMD -鼠标左键单击。虽然这不能完全解决我的问题,但总比什么都没有好。
发布于 2021-09-24 22:48:40
在此基础上,实现了点击项目切换选择的功能。
class MyItem: NSCollectionViewItem {
override var isSelected: Bool {
didSet {
self.view.layer?.backgroundColor = (isSelected ? NSColor.blue : NSColor.gray).cgColor
// If the selection causes the size to change, re-layout.
self.collectionView?.collectionViewLayout?.invalidateLayout()
}
}
override func viewDidLoad() {
self.view.wantsLayer = true
self.view.addGestureRecognizer(NSClickGestureRecognizer(target: self, action: #selector(onClick(sender:))))
}
@objc private func onClick(sender: NSGestureRecognizer) {
guard let indexPath = self.collectionView?.indexPath(for: self) else { return }
if self.isSelected {
self.collectionView?.deselectItems(at: [indexPath])
} else {
self.collectionView?.selectItems(at: [indexPath], scrollPosition: [])
}
}
}https://stackoverflow.com/questions/38708731
复制相似问题