Perform actions on a UICollectionViewCell using Closures

Swift Diaries
Arimac
Published in
3 min readMar 11, 2020

--

Closures are one of best features in Swift programming language. It can be used in many ways to make life easy.

Closures can capture and store references to any constants and variables from the context in which they are defined. This is known as closing over those constants and variables. Swift handles all of the memory management of capturing for you.

This is what the Official Swift Doc says about closures.

closures.png

Before the introduction of closures we had to use Protocol and Delegate pattern to communicate among view controllers or components. By using closures it makes more easy to understand the code and reduce number of code lines.

I will take a UICollectionViewCell for this example. But this can be adopted any where for actions or variables passage among components. I’ll take this mockup to do this explanation.

This cell will have three UIButtons to perform three independent actions.

  1. change text value of a label
  2. present a custom alert made using UIViewController
  3. trigger a network request

In the 1st case, think the new label text value resides in the MainViewController where the collection view cell is returned. In the old fashioned way we have to define a protocol to make this happen.

In the 2nd case, because the cell inherits from UICollectionViewCell, we can't present a UIViewController from the cell itself.

In the 3rd case, the network request may be written or bound to the MainViewController.

Common problem of these three cases is that we can't trigger any action within the collection view cell. Solution for this problem is using a closure to pass the actions or values. These code examples may help to understand the solution.

On three button actions, three closures are called. These calls will be captured in the MainViewController as follows.

This way is much cleaner than implementing protocols and delegating methods. This example covers passing values among components. In the 1st example getting a new value to the cell and in the 2nd example returning a value from the cell to an outer component.

This makes easy to reuse this cell again and again. As an example if you need to use this cell again in another place, but the message you need to pass or the network request is different, you may use this method. If network request was implemented within the cell, you can’t specify which request to call.

I think you could get an idea of the power of closures and also a clean and easier way to go around components rather than typical protocol delegate way.

--

--

Swift Diaries
Arimac

I am an iOS developer and thought of writing day today Swift things for the community :)