Building TableViewCells/CollectionViewCells in a Lean and Reusable way

Kumar Reddy
2 min readJun 5, 2021

As an iOS developer, one should have involved in building a collection of items using either UITableView or UICollectionView in the apps. Though we are using them almost every day in our development, I feel that there is an opportunity for us to make them leaner and reusable way.

To understand the problem, let's dive into the real-time example. The requirement is to show a list of restaurants on the app home screen.

  1. We will pick the UITableView for displaying the list of restaurants.
  2. Put the UIWireframe into XIB or Programmatic way.
  3. Create a RestaurantTableViewcell from UITableViewCell
  4. Implement data source and build the Restaurant Listing screen.

This looks pretty much typical developer workflow and it should work.

Let’s assume that if we get another requirement to display the same Restaurant View in UICollectionView in some other part of the application or to show the Restaurant View in the Restaurant Details Screen which is simple UIViewController the above solution does not work.

We can not use UITableViewCell inherited classes for UICollectionView and vice versa

The View is the same but exists in multiple places, more maintenance, and easy to fail.

To make that work, we need to create one for TableView, one for CollectionView, and another for ViewController.

As we all know that everything that we see on the screen is an UIView object. Let’s build the UIView for the wireframe and then make use of the View in UITableViewCell or UICollectionViewCell or anywhere.

One view getting used in multiple different ways

Let’s dive into code for more details.

We are going to embed the above view in the UITableViewCell

Benefits of New Approach

  1. We separated our main view and the logic agnostic of the outer rendering part, it can be a TableView or UICollectionView or IGListKit or actually anything.
  2. The created UIView is now reusable across the app. This is so much helpful when we were using the common UIView components across the application. The view now is not bound to any super view, it can embed into TableViewCell or CollectionViewCell.

Thank you for reading the article. Let me know what do you think about the approach.

--

--