Creating Custom UITableViewCells Programatically

Be it with a UICollectionView or a UITableView, working with reusable cells is a threshold concept any iOS developer has to get through. Therefore, this post will show you how to get up and running.

I will assume you know how to setup and use a UITableView. Therefore it will focus on the creation of a custom cell.

Create A Custom Cell Class

Firstly we need to create a class to work with. In this example I’ll call it ‘CustomCell’. You can rename this for your purpose, for instance ‘MessageCell’ might be appropriate. Create a new file called ‘CustomCell’ and add the following:

This is just about the minimum you need in your class. Because UITableViewCell inherits from a UIView, you have to implement the required init with coder initialiser. However, here we are focusing on building the view with code. As a result we’ll leave the fatal error if one is created from an interface builder file.

Register The Class With the Table View

Secondly, you have to “register” your custom class with the table view. What!?

Put simply, this means “tell the table view to use your custom cell class”. There are two options for registering cells. One registers a cell class. The other registers a nib file. Since we aren’t using any interface builder files here, we need the former one.

In your view controller register the class as follows:

Now, when you dequeue a cell to use you can cast it as your custom cell as follows:

Prepare Cells For Reuse

Cells are recycled by the table view, therefore you cant always be sure what state they’ll be in when they get to you…enter perpareForReuse().

This method is super useful, so make use of it if applicable. Think of it as the place to setup a clean slate before displaying the cell. For example, if you set the adjusted the alpha of the cell after an interaction, this would be the place to reset it before it is displayed again.

For performance reasons, you should only reset attributes of the cell that are not related to content, for example, alpha, editing, and selection state.

Apple Developer Documentation

If you implement the prepareForReuse() method, you must call the super implementation. To get you started…