Monday, 11 November 2013

Custom UITableViewCells

I've decided to write a blog post about the best way to create a custom UITableViewCell using a xib. I haven't been able to find a tutorial that covers all the steps, and since this is a very common thing, I'm going to outline them here.

To start, I'm going to assume you have a project set up, and you have a view controller that contains a UITableView.

First thing you are going to do is create the cell.

1) Go File > New > File... > Cocoa Touch > Objective-C class.

2) In the "Subclass of" field, type UITableViewCell. In the "Class" field, type the name of your custom cell. Click next, and make sure to include it in your target.

3) Once the class file has been added, you can add the .xib. Go File > New > File... > User Interface > View. Make sure to name the view the same as your custom cell's class name (for organization purposes).

4) In the .xib, click on the view, and delete it. Then, from the Object Library (on the bottom right), drag a UITableViewCell onto the canvas.

5) Click on the cell in the document tree, then in the Identity Inspector (top right), type your custom cell's class name in the class field. It should autocomplete to the name.

6) In the .xib, click on "File's Owner". In the Identity Inspector, set the class to be your View Controller that contains the UITableView.

7) Now, In Assistant Editor mode, switch the second view to your ViewController.m class. It should be located under Automatic in the file tree. If you don't see it there, try clicking on "File's Owner" (the yellow cube on the left), and try again.

8) Connect the UITableViewCell in the .xib to your viewController class as an IBOutlet (control+drag from the cell to your .m file). Make sure to also import your CustomCell.h in ViewController.m.

9) Customize the UITableViewCell with UILabels, UIImageViews, etc, and make sure to connect everything to CustomCell.h, not the View Controller class. Make sure to add a custom identifier in the Identifier field in the Attributes Inspector. Also, make sure to name your views uniquely. If you were to name your UIImageView "imageView", the results are unexpected since UITableViewCell already has this property.

10) Now, we're going to make a UINib property to hold on to the nib so that we don't have to load it for every cell.

11) Now we're going to implement the two required UITableViewDataSource methods. They should look like this.

Run your app, and you should get something similar to the image below: