title: Invisible cells of UICollectionView stay selected
body: <p>I have a <strong>UICollectionViewController</strong> which uses a custom cell. There is a function get called when the user taps on a cell, to distinguish the selected cell I change the background color of the cell to the green. 
  The problem is, when user taps on another cell, the previous one should be unselected, another function will be called. as long as the collectionView is not scrolled it works fine, but when the user scrolls the collectionView and selected one goes out of the visible rect of the screen, my deselect function does not work and there will be two cells with a green background. </p>
  
  <p>It's the demo:</p>
  
  <p><a href="https://i.stack.imgur.com/gZg2j.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/gZg2j.gif" alt="enter image description here"></a></p>
  
  <p>You can see there is a cell with green background at the top, and another one at the end.</p>
  
  <p>Here are methods for selecting and deselecting cells:</p>
  
  <pre><code>override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
  
      if let cell = collectionView.cellForItem(at: indexPath) as? CategoryCollectionViewCell {
              cell.selectItem()
      }
  }
  
  override func collectionView(_ collectionView: UICollectionView, shouldSelectItemAt indexPath: IndexPath) -&gt; Bool {
      for _cell in collectionView.visibleCells {
          if let __cell = _cell as? CategoryCollectionViewCell {
              __cell.deselectItem()
          }
      }
  
      if let indexPath = collectionView.indexPathsForSelectedItems {
          if indexPath.count &gt; 0 {
              if let _cell = collectionView.cellForItem(at: indexPath.first!) as? CategoryCollectionViewCell {
                  _cell.deselectItem()
              }
          }
      }
  
      return true
  }
  </code></pre>