Pablo Garcia

Apps for iPhone, iPad, Apple TV and Apple Watch

Tutorial - Custom Cells with XIB

Nov 30, 2018

In this tutorial I'm going to explain how to create custom cells with xibs files in a few easy steps.

Create the project

  • Open Xcode and create a Single View App.
  • Open Main.storyboard file
  • Drag and drop an UITableView
  • Drag and drop an UITableViewCell

Connect the UITableView with the ViewController

  • Select the Main.storyboard file and press Show assistant editor button. You will have something like this

  • Create the tableView IBOutlet in your ViewController

Create XIB file

  • Create a new User interface file. File-> New File and name it BandCell.

  • Drop an UITableViewCell

  • Insert two UILabels like this

Create the BandCell class

  • Create a new Cocoa Touch class and name it BandCell
  • In the BandCell.xib file
    • open the Identity Inspector tab and in custom class type BandCell.
    • open the Attribute inspector tab and in Identifier type BandCellId

  • Create an IBOutlet in BandCell class

     @IBOutlet weak var rockBandName: UILabel!
  ```


- Add a function to configure the data

swift public func configureCell(name: String) { rockBandName.text = name }




### Configure tableView, and tableview's delegate and datasource

Once we have configured everything, we are ready to do the final step.

- Register the BandCell nib and add a few data for our tableView


swift private var data = ["Dire Straits", "AC/DC", "Joe Satriani", "Bruce Springsteen", "Julian Lage", "Menilmontant Swing", "Pink Floyd"]

override func viewDidLoad() { super.viewDidLoad() tableView.delegate = self tableView.dataSource = self tableView.register(UINib.init(nibName: "BandCell", bundle: nil), forCellReuseIdentifier: "BandCellId") }




swift extension ViewController: UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return data.count }

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "BandCellId") as! BandCell

cell.configureCell(name: data[indexPath.row])

return cell }

} extension ViewController: UITableViewDelegate {

}



And thats all. If you run the project something like this will appear


<p align="center">
  <img width="400" src="/images/posts/customcells/final.png">
<