如何通过再次单击取消选择 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
}
}
此代码在单击另一个项目时取消,但在单击同一项目时不取消。单击同一项目时,我想取消选择。