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; 
} 
相關問題