Selectively Add & Remove Gradient — UICollectionViewCell

Written by p.gpt10 | Published 2018/05/13
Tech Story Tags: swift | programming | ios-app-development | uicollectionviewcell | add-remove-gradient

TLDRvia the TL;DR App

The details are not the details. They make the design.

Playing with Collection Views is so much fun and challenging. One of the things I came across is using gradients with collection views.

Adding gradient to a [UICollectionView](https://developer.apple.com/documentation/uikit/uicollectionview) or [UICollectionViewCell](https://developer.apple.com/documentation/uikit/uicollectionviewcell) is as simple as adding it to any other view. We had a detailed discussion over it in the previous article.

Another challenge is, what if we need to add gradient to a UICollectionViewCell on selection and remove it when the UICollectionViewCell is de-selected.

So, do you find that challenging? Let’s see step-by-step how we can achieve that.

Pre-requisites

Before we start coding, let’s see what we already have 🧐 and how can we use that to solve our problem statement.

  1. Adding gradient to a view — In the previous article we had a detailed discussion on how to get that working.
  2. Changing the **UICollectionViewCell’s** properties based on its selection stateHere we have already discussed how isSelected handles that.

Combining the above 2, now we’re left with “adding the gradient to cell when it is selected and removing it when it is de-selected”. We’re already halfway there, just need to put our knowledge in the right place. 🎯

Now that we know what actually needs to be done, let’s begin with some coding.

Let’s code it..

Our custom UICollectionViewCell, should implement 2 things,

  1. A gradient that we want to apply on each cell
  2. Override isSelected to handle selection state changes, i.e.

That’s it. That’s the only code we require to get that working.

Sample Project

You can download the sample project from here.

Promotions

Don’t forget to read my other articles:

  1. Everything about Codable in Swift 4
  2. Everything you’ve always wanted to know about notifications in iOS
  3. Coding for iOS 11: How to drag & drop into collections & tables
  4. All you need to know about Today Extensions (Widget) in iOS 10
  5. UICollectionViewCell selection made easy..!!

Feel free to leave comments in case you have any doubts.


Published by HackerNoon on 2018/05/13