iOS Cell Registration & Reusing with Swift Protocol Extensions and Generics
A common task when developing iOS apps is to register custom cell subclasses for both UITableView and UICollectionView. Well, that is if you don’t use Storyboards, of course.
Both UITableView and UICollectionView offer a similar API to register custom cell classes:
A widely accepted solution to handle cell registration and dequeuing is to declare a constant for the reuse identifier:
Let’s try to generalize this code and make it simpler and safe.
First of all, it would be nice to get away with declaring a constant for every reuse identifier in our app. We can just use the name of the custom cell class as a default reuse identifier.
We can create a protocol for Reusable Views and provide a default implementation constrained to UIView subclasses.
By making UICollectionViewCell conform to the ReusableView protocol, we get a unique reuse identifier per cell subclass.
Next, we can get rid of the hard-coded string we are using to load the Nib.
Let’s create a protocol for Nib Loadable Views and provide a default implementation using protocol extensions.
By making our BookCell class conform to the NibLoadableView protocol we now have a safer way to get the Nib name.
If you use a different name for the XIB file than the one provided by Xcode, you can always override the default implementation of the nibName property.
With these two protocols in place, we can use Swift Generics and extend UICollectionView to simplify cell registration and dequeuing.
Notice that we created two versions of the register method, one for cell subclasses implementing just ReusableView and another one for cell subclasses implementing both ReusableView and NibLoadableView. This nicely decouples the view controller from the specific cell registration method.
Another nice detail is that the dequeueReusableCell method doesn’t need to take any reuse identifier and uses the cell subclass type for the return value.
Now the cell registration and dequeuing code looks much better :).
If you are coming from Objective-C it is worth to investigate powerful Swift features like Protocol Extensions and Generics to find alternate and more elegant ways to deal with Cocoa classes.
Here you can find the markdown version of this story.