Have any Question?

You can ask below or enter what you are looking for!

Custom UITableViewCell from xib file in Swift 3

Create the custom UITableViewCell from a xib file

In this tutorial we will create a custom cell from xib file and learn how to use it in UITableView using Swift 3

Create Xcode project

1- Create a new Xcode project and select “Single View Application” template and click next

2- Type you project name, in my case i named it “CellExample” and select Swift from Language list and iPhone from Devices list and click next

custom uitableviewcell from xib in swift

3- select a location for your project then click finish.

Create UITableViewCell class and xib

4-Now create a new file and select “Cocoa Touch Class” and press next

custom uitableviewcell from xib in swift

5- Select UITableViewCell from “Subclass of” list and enter a name for your custom cell like “MyCustomCell” and press next

custom uitableviewcell from xib in swift and xcode

6-Select a location for your new file and press “Create”

7- Now create another new file and select “Empty ” from user interface section and press Next

custom uitableviewcell from xib in swift table view

8- Give it the name as the file created before “MyCustomCell” and press Create

9- Select the xib file if its not selected and drag UIView on it and from the “Identity inspector” change its Class name to the same class name of the swift file “MyCustomCell”

xcdoe swift

10- From the “Attributes inspector” change size to Freeform and “Status bar”, “Top bar” and “Bottom bar” to none

custom uitableviewcell from xib in swift

11-From “Size inspector” change Height to whatever you want, i will change it to 100

12- Now add another UIView inside it to hold all our controls, position it at (0, 0) and give it the same height and width as its parent and add 4 constraints from 4 sides

custom uitableviewcell from xib in swift

13- Add 2 UILabels and add their constraints, the view should look like this

custom uitableviewcell from xib in swift

14- Now press the MyCustomCell.swift code and add 2 IBOutlets for your labels so the file should look like this.

import UIKit
class MyCustomCell: UITableViewCell {
@IBOutlet weak var lblFirstName: UILabel!
@IBOutlet weak var lblLastName: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}

15- Press the xib file and for every UILabel select it and from “Connections inspector” drag from “New Referencing Outlet” to the main view “MyCustomCell” and select the appropriate outlet “lblFirstName” and “lblLastName”.

custom uitableviewcell from xib in swift


Create UITableView and use our custom cell

16- Open ViewController.swift and add outlet to UITableView then add the UITableViewDelegate and UITableViewDataSource to the header of the class.

import UIKit
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
    @IBOutlet weak var tblUsers: UITableView!
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}

17- Open “Main.storyboard” and drag “Table View” on “View Controller” main view and let it occupy the full size of the view and add appropriate constraints.

18- control+drag from table view to view controller and select data source then repeat and select delegate.

19- control+drag from view controller to the table view and select tblUsers.

20- The most important part here is to register the xib containing the custom cell with the table view therefore we add the following code in viewDidLoad() method.

let nib = UINib.init(nibName: "MyCustomCell", bundle: nil)
self.tblUsers.register(nib, forCellReuseIdentifier: "MyCustomCell")

21- Create an array to be our data source by adding this line of code just before viewDidLoad()

var usersArray : Array = [["first_name": "michael", "last_name": "jackson"], ["first_name" : "bill", "last_name" : "gates"], ["first_name" : "steve", "last_name" : "jobs"], ["first_name" : "mark", "last_name" : "zuckerberg"], ["first_name" : "anthony", "last_name" : "quinn"]]

22- Finally configure the table view by adding the following methods

    // MARK: - UITableView delegate
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return usersArray.count
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 100
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell = tableView.dequeueReusableCell(withIdentifier: "MyCustomCell", for: indexPath) as! MyCustomCell
        
        let dict = usersArray[indexPath.row]
        
        cell.lblFirstName.text = dict["first_name"]
        cell.lblLastName.text = dict["last_name"]
        
        return cell
    }

23- that was the last step and if you press run you will get something like this screen

swift tutorial

Hope you find it useful tutorial and tell me in comment if you have any question

Good to know UIViewController lifecycle

(7) Comments

  1. Hello,

    This is a very nice tutorial. The steps are easy to follow, however, I noticed that nothing is happening when I tried to control + drag My Custom Cell to the referencing outlet (step#15). Moving forward, the app displays the content of the table on load, however, upon scroll or click on the table, the content disappears. Do you have any idea how to fix this issue?

    Thank you very much.

    • Hello,
      You should drag from the circle next to “New Referencing Outlet” to your “Custom Cell” and don’t press Ctrl while dragging

      Regarding your second question i think the problem will be in your cellForRow function, i think you are creating a new label every time a cell is created, this is an example of how your cellForRow should look like:

      func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
              
              let cell = tableView.dequeueReusableCell(withIdentifier: “MyCustomCell”, for: indexPath) as! MyCustomCell
              
              let dict = usersArray[indexPath.row]
              
              cell.lblFirstName.text = dict[“first_name”]
              cell.lblLastName.text = dict[“last_name”]
              
              return cell
          }
      
  2. You are saying that we should register for that cell to Tableview object. But what if I want to use multiple custom cells with Xib.

Leave a Reply

Your email address will not be published. Required fields are marked *