Create a CustomUITableViewCell in a UITableView
Difficulty: Beginner | Easy | Normal | Challenging
Creating a custom UITableViewCell can be a little bit tricky when done from the storyboard — but this article is here to help you out!
The idea is to have a
UIViewController with a
UITableView, and be able to move once the
UITableViewCell is clicked move to a Detail
For fun, this is going to display a well-chosen list of animals (just the obvious animals here: Dogs, Cats and Galapagos Giant Tortoises are of course included). The
DetailViewController will simply display the name of the animal in a
Setup: the basic classes for the UIViewController and UITableViewCell
CustomTableViewCell class looks like the following
Which is, as you might expect, a single line label when viewed in the storyboard
Which needs a storyboard identifier within the storyboard to be set — this will need to be set as cell if you follow along with the article.
The rest of the code for the
ViewController is as follows:
The date is an array of strings at the top, given the name
data. We also have a
tableView instance (sorry about the force-unwrapping, but we know that it will be instantiated in the
viewDidLoad() function). Within the
viewDidLoad() function the tableView is set up, and the cell is set up to be resused in
UITableViewDataSource functions are fairly self-explanatory
tableView(_:numberOfRowsInSection:) sets the rows with the same number as the data. Then
tableView(_:cellForRowAt:) places the data into the
UITableViewCell, that is assigning
animalLabel. An alternative to this would be using an initialiser with the cell as
Setup: the add a DetailViewController
DetailViewController will use a new
ViewController subclass which is then set as the class for a name for that second view controller.
Setup: the segue between ViewController and DetailViewController
ViewController will traverse to
DetailViewController using a Segue. This is done through a drag + drop action from
ViewController to the
In this case the segue has been named as
DetailViewController has a property for
dataString that we will use to be displayed on a table.
Making sure that the
DetailViewController on the storyboard is connected to the
Pass data between the ViewControllers
ViewController will pass data to
DetailViewController through the
This will (of course) only happen when we have clicked on the row, using
Placed in an extension for the
ViewController we make the segue, passing the data through the segue.
Using a segue is just one way to pass information around a project, but has been chosen here to amply demonstrate how a custom
UITableViewCell can be implemented even going so far as pressing the cell to traverse to the next
Certainly you can do more with
UITableViewCell, but this is just a start. To what? You decide with your own App implementations. Good luck!
Want to view the whole project? Look at the Repo
Any questions? Get in touch with me on Twitter and I’ll help you out!