iOS Table and Collection View Cell info from nib

gridWhen creating UITableViewCell or UICollectionViewCell subclasses you usually need to define a few things both in xib and in code. First when you create the layout in the interface builder, you also define the reuse identifier for that cell. Implicitly for UITableViewCell and UICollectionViewCell you define the height/size. Automatically generated xib has the same file name as the name of the class. These are all things that you have to define in two places – one is the xib itself, and the other is in code.

Single source of truth, a common practice in computer science, states that every data element should be stored exactly once. Each part of the project that needs this specific information or data element should reference it from that single location. This is a problem for UITableViewCell or UICollectionViewCell subclasses in the way they are usually implemented.

Using the class initialize method, with a small penalty of instantiating a single cell object, the three main parameters are referenced from the xib: reuse identifier, nib, and cell size (for collection view cells) or cell height (for table view cells).

For convenience I add the implementation below to the code snippet library in Xcode so I can access it with a shortcut. There is no need to change anything in this code since it uses generics and works on any UICollectionViewCell / UITableViewCell subclass.

UICollectionViewCell subclass implementation


UITableViewCell subclass implementation

This way you can register the cell with a table view using the references from the exact cell subclass.

As you can see in the code above, if you change cell reuse identifier in the xib, or change the layout in the xib that affects the height of the cell, these changes will be immediately propagated to the code because they are referenced. With the usual approach, you’d need to change the reuse identifier string and height in the code. I’ve seen many times that developers change the height in the xib but forget to update it in code, a change that is sometimes seen only after the app has been released. It’s something that can and should be eliminated.

Now you can easily dequeue a cell with cellReuseIdentifier reference.

Check out a sample project on my GitHub repo:

If you liked this blog post I’d appreciate if you followed me on Twitter

Related Post

Remember to share...Share on FacebookTweet about this on TwitterShare on Google+Share on LinkedInEmail this to someone

Leave a Reply

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