title: Toggle select / deselect state of a UICollectionView Cell on tap - Swift
body: <p>So first of all i've been stuck on this for a few days and spent a full day reading and trying many options on Stack Overflow already but non to my success</p>
  
  <p>What i'm trying to accomplish sounds simple and going over the Apple documentation it seems to me it should work
  <a href="https://developer.apple.com/library/ios/documentation/UIKit/Reference/UICollectionViewDelegate_protocol/#//apple_ref/occ/intfm/UICollectionViewDelegate/collectionView:shouldHighlightItemAtIndexPath" rel="nofollow">https://developer.apple.com/library/ios/documentation/UIKit/Reference/UICollectionViewDelegate_protocol/#//apple_ref/occ/intfm/UICollectionViewDelegate/collectionView:shouldHighlightItemAtIndexPath</a>:</p>
  
  <p>Basically what i'm trying to achieve is to toggle the selected state of a UICollectionView Cell on tap.</p>
  
  <p>First tap - Send the cell into a selected state and change background colour to white.</p>
  
  <p>Second tap - Send the cell into a deselected state and change background colour to clear</p>
  
  <p>ViewController -</p>
  
  <pre><code> func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -&gt; UICollectionViewCell {
      if let cell = collectionView.dequeueReusableCellWithReuseIdentifier("Cell", forIndexPath: indexPath) as? CollectionViewCell {
          cell.cellImage.image = UIImage(named: images[indexPath.row])
          return cell
      } else {
          return CollectionViewCell()
      }
  }
  
  func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
      if let cell = collectionView.cellForItemAtIndexPath(indexPath) as? CollectionViewCell {
          cell.toggleSelectedState()
      }
  }
  
  func collectionView(collectionView: UICollectionView, didDeselectItemAtIndexPath indexPath: NSIndexPath) {
      if let cell = collectionView.cellForItemAtIndexPath(indexPath) as? CollectionViewCell {
          cell.toggleSelectedState()
      }
  }
  </code></pre>
  
  <p>Cell - </p>
  
  <pre><code>    func toggleSelectedState() {
      if selected {
          print("Selected")
          backgroundColor = UIColor.whiteColor()
      } else {
          backgroundColor = UIColor.clearColor()
          print("Deselected")
      }
  }
  </code></pre>
  
  <p>The problem i'm having is the didDeselectItemAtIndexPath is not being called when tapping on a cell thats already selected, Though if i tap another cell it will get called and selects the new cell...</p>
  
  <p>I have tried checking for selected states in shouldSelectItemAtIndexPath &amp; shouldDeselectItemAtIndexPath, i even tried writing a tapGesture to get around this and still no luck...</p>
  
  <p>Is there something i'm missing?
  Or is there any known work arounds to this?
  Any help would be greatly appreciated!</p>