paint-brush
UICollectionViewCell selection made easy..!!by@p.gpt10
47,891 reads
47,891 reads

UICollectionViewCell selection made easy..!!

by Payal GuptaJuly 31st, 2017
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

I have been working with <em>UICollectionView</em> and <em>UICollectionViewCell</em> for quiet a long time now.
featured image - UICollectionViewCell selection made easy..!!
Payal Gupta HackerNoon profile picture

I have been working with UICollectionView and UICollectionViewCell for quiet a long time now.

Showing selection of a particular collection view cell is a very frequent issue faced by those working with collection views. I am refering to something like this,

How to ?

In your custom UICollectionViewCell subclass, just override isSelected property, i.e.

isSelected is a UICollectionViewCell’s stored property that represents the cell selection state. The selected state is toggled when the user lifts up from a highlighted cell.

In your UICollectionViewCell subclass, you just need to override this property and provide your custom implementation. Example: You can set property observers on it so that you are notified of any changes made in the property for a particular cell, i.e.

How does isSelected works?

Whenever a particular UICollectionViewCell is selected by the user:

  1. isSelected = true, for the selected cell.
  2. isSelected = false, for the rest of the cells in UICollectionView.

So, as a result, the isSelected will be set either true/false for all the cells , every time a cell is selected by the user.

How to respond according to cells’ selection status ?

To achieve the desired result:

Now, to show when a cell selected/de-selected, you just need to change some of the properties of the cell according to you requirements.

Example:

I have used cell’s transform, backgroundColor and a custom imageView isHidden state properties to highlight the cell’s selection state. You can use others as well according to your requirement.

Promotions

Don’t forget to read my other articles:

  1. Drag It & Drop It in Collection & Table — iOS 11
  2. Everything about Codable in Swift 4
  3. Color it with GRADIENTS — iOS
  4. Everything you’ve always wanted to know about notifications in iOS
  5. All you need to know about Today Extensions (Widget) in iOS 10
  6. Selectively Add & Remove Gradient — UICollectionViewCell

Watch this space for more on UICollectionView and UICollectionViewCell. Feel free to drop your queries if you have any.