Instructions on how to create custom UITableViewCell with a xib

It is a very fast and convenient way to create a custom UITableViewCell layout using Interface Builder. But Apple for some reason has not made this easy – you have to know some magic things to perform this task. There is a a ton of tutorials on this topic already. But nevertheless I decided to write my own one. So, these are step by step instructions:

1. Create a UITableViewCell subclass, let’s name it RRMessageCell. When you create it, you will not get a xib by default, because XCode doesn’t create it.
2. Add a xib file called RRMessageCell.
3. In your xib file delete a view by default and add UITableViewCell object.
4. Set a class for that new cell in xib and for File’s owner RRMessageCell in a right panel, 3rd tab of the Interface Builder.
5. Add elements to your cell in xib: labels, imageViews, etc.
6. Create outlets in your RRMessageCell class.
7. Here is a first magic: do not bind outlets via files’ owner, but bind them via your RRMessageCell. It should look like this when you right click of your file’s owner:

And it should look like this when you right click of a cell view:

8. Now second magic: select your cell view in a xib file and in a 4th tab of right panel (attributes) set Identifier to ‘RRMessageCell‘. Here is illustration:

9. Now you can close a xib file, open implementation file and write some code to set contents of a cell, using a custom setter for object, that is displayed in your cell class RRMessageCell.m:

10. And now third magic – you have to create a cell this way in your UITableViewController:

P.S. Small tip: do not use “textLabel“, “detailTextLabel” variables in your custom UITableViewCell classes, because they will interrupt with native textLabel and you will get SIGABRT bug in runtime.

P.S.S. If frames are drawn incorrectly, try to override layoutSubviews method of your custom class or remove autoresizing masks. This is another topic.

Leave a Reply

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