iOS UITableViewCell, UICollectionViewCell, UITableViewHeaderFooterView and UICollectionReusableView dequeing and registering — Using Swift protocol & Generics

Old way of doing register cell

If you are an iOS developer, you would come across UITableView and UICollectionView everyday in your life. You would need to register your Cell or UITableViewHeaderFooterView or UICollectionReusableView reuse the cell using an ugly identifier string declared somewhere using static properties. So your code would be something like this

The viewcontroller will become more messy when there are more cells need to be registered and reuses. So a better way to manage it would be making use of Swift’s generics and protocols which will help us to reuse and register the cells, header footer view and supplementary view very easily.

Using the power of Generics and protocols

First we create a Protocol Named ReusableView

The Protocol has a get only property named defaultReuseIdentifier which returns the description of the Cell/HeaderFooterView/ReusableView Class which would be uique for each class.

Extend UITableView and UICollectionView and add the following functions which accepts generic parameter T for registering both Class and Nib Cells. This function will will pass the class type as generic parameter and registers to the table view or the collection view by using the defaultReuseIdentifier .

Similarly we can also register UITableViewHeaderFooterView and UICollectionReusableView for the TableView and CollectionView. Add the below function in the UITableView and UICollectionView extensions.

Now we add the methods for dequeing the cells / HeaderFooterView / Suppelementary Reusable View in the same UITableView and UICollectionView extensions which accepts a Generic Class T, which should confirms to either ReusableView or NibLodableView (Check Usage Section).

Usage

Confirm the Custom cells to ReusableView and NibLodableView and the Cells/Suppelmentary Views/HeaderFooterView are ready to use.

Once the extensions and protocol confirmations are in place, you can start using them in your Viewcontroller like below.

Auto suggestion for register methods

Complete ReusableView.swift Class to include in the project :

Hope this would help you to reduce the code cluttering and easy usage of registering and reusing TableView and CollectionView Cells, HeaderFooterViews and ReusableSupplementary Views without need to maintain ugly static string constant in every cell class.