1

如何通过再次点击取消选择NSCollectionViewItem?通过点击取消选择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 
     } 
    } 

此代码deslect另一个项目被点击时,而不是在相同的产品。我想在点击同一项目时解散。

回答

0

一个简单的技巧就是使用CMD - 鼠标左键单击。虽然这并不能完全解决我的问题,但它总比没有好。

0

您可以通过观察项目上的选定状态,以及在选择项目的视图时安装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; 
} 
相关问题