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; 
} 
関連する問題