Creating Custom UITableViewCell With Xib Swift

This tutorial will look at how to setup a custom UITableViewCell class with an accompanying XIB (Interface Builder file).

It will assume that you have a basic working knowledge of table views. So we’ll begin from having one set up. This will be the starting point for our ViewController class:

Here we have a UITableView connected as an @IBOutlet from our storyboard. The two required data source methods have been implemented as well.

Note: Be sure the set the data source and delegate for your table view. Either do this in your storyboard or in you’re viewDidLoad method:

Set the Reuse Identifier For The Cell

Make sure you give the cell an appropriate reuse identifier, here we’ll just use “Cell”:

Head over to your storyboard and select the cell from your tableview. Go to the attribute inspector on the right and be sure to give it the same reuse identifier as you used in the code above. In this case “Cell”.

Create The CustomCell Class

Create a new Swift file. File > New > File…

Paste in the following:

This CustomCell inherits from a UITableViewCell. The prepareForResuse() method is worth pointing out. We’re not going to use it in this simple setup, but it’s likely to come in handy when you start doing more interesting things with your layouts. From the documentation:

…this method is invoked just before the object is returned from the UITableViewmethod dequeueReusableCell(withIdentifier:).

Create the new XIB File

Create a new interface builder file. File > New > File… and select View under the Interface Builder section.

Select the view and assign your CustomCell class to it in the Identity Inspector section:

From here you are in the position to set up IBOutlet’s and IBAction’s to this CustomCell class, as you would usually do to a UIViewController.

Add Some UI

Select your custom view and go to the assistant editor. This should display your interface builder file alongside your custom class. You can ctrl + click & drag to set up IBOutlets and IBActions as your should be familiar with from working with view controllers. In this example we’ll just create a simple UILabel called myLabel:

Prepare Your Cell

Change your tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) to the following:

The important change here is we’re now casting it as our own CustomCell class. We can now access the properties and methods of that cell outlined in our CustomCell class. Lets set the text of the table that we set up to display the row number. Add the following before the return statement:


If you build and run your app, you should now see your custom XIB being used for the cell. Of course you can hook up and UI elements you need, buttons, segment controls etc.