Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save tangzzz-fan/ffc89685dbf5dcd8a470bc2298bc73ab to your computer and use it in GitHub Desktop.
Save tangzzz-fan/ffc89685dbf5dcd8a470bc2298bc73ab to your computer and use it in GitHub Desktop.
iOS Cell Registration & Reusing with Swift Protocol Extensions and Generics

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:

public func registerClass(cellClass: AnyClass?, forCellWithReuseIdentifier identifier: String)
public func registerNib(nib: UINib?, forCellWithReuseIdentifier identifier: String)

A widely accepted solution to handle cell registration and dequeuing is to declare a constant for the reuse identifier:

private let reuseIdentifier = "BookCell"

class BookListViewController: UIViewController, UICollectionViewDataSource {

    @IBOutlet private weak var collectionView: UICollectionView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        let nib = UINib(nibName: "BookCell", bundle: nil)
        self.collectionView.registerNib(nib, forCellWithReuseIdentifier: reuseIdentifier)
    }

    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath)
    
        if let bookCell = cell as? BookCell {
            // TODO: configure cell
        }
    
        return cell
    }
}

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.

protocol ReusableView: class {
    static var defaultReuseIdentifier: String { get }
}

extension ReusableView where Self: UIView {
    static var defaultReuseIdentifier: String {
        return description()
    }
}

extension UICollectionViewCell: ReusableView {
}

By making UICollectionViewCell conform to the ReusableView protocol, we get a unique reuse identifier per cell subclass.

let identifier = BookCell.defaultReuseIdentifier
// identifier = "MyModule.BookCell"

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.

protocol NibLoadableView: class {
    static var nibName: String { get }
}

extension NibLoadableView where Self: UIView {
    static var nibName: String {
        return NSStringFromClass(self).componentsSeparatedByString(".").last!
    }
}

extension BookCell: NibLoadableView {
}

By making our BookCell class conform to the NibLoadableView protocol we now have a safer way to get the Nib name.

let nibName = BookCell.nibName
// nibName = "BookCell"

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 UITableView and UICollectionView to simplify cell registration and dequeuing.

extension UITableView {
    
    // MARK: - Register cells & views
    
    func register<T: UITableViewCell>(_: T.Type) {
        register(T.self, forCellReuseIdentifier: T.defaultReuseIdentifier)
    }
    
    func register<T: UITableViewCell>(_: T.Type) where T: NibLoadableView {
        let bundle = Bundle(for: T.self)
        let nib = UINib(nibName: T.nibName, bundle: bundle)
        register(nib, forCellReuseIdentifier: T.defaultReuseIdentifier)
    }
    
    func register<T: UITableViewCell>(_ cellClasses: [T.Type]) {
        cellClasses.forEach { register($0) }
    }
    
    func registerHeaderView<T: UITableViewHeaderFooterView>(_: T.Type) {
        register(T.self, forHeaderFooterViewReuseIdentifier: T.defaultReuseIdentifier)
    }
    
    func registerHeaderViews<T: UITableViewHeaderFooterView>(_ viewClasses: [T.Type]) {
        viewClasses.forEach { registerHeaderView($0) }
    }
    
    func registerFooterView<T: UITableViewHeaderFooterView>(_: T.Type) {
        register(T.self, forHeaderFooterViewReuseIdentifier: T.defaultReuseIdentifier)
    }
    
    func registerFooterViews<T: UITableViewHeaderFooterView>(_ viewClasses: [T.Type]) {
        viewClasses.forEach { registerFooterView($0) }
    }
    
    // MARK: - Dequeue cells & views
    
    func dequeueReusableCell<T: UITableViewCell>(ofType cellType: T.Type,
                                                 for indexPath: IndexPath) -> T {
        guard
            let cell = dequeueReusableCell(withIdentifier: cellType.defaultReuseIdentifier,
                                           for: indexPath) as? T
        else { fatalError("Can't dequeue cell of type: \(cellType)") }
        return cell
    }
    
    func dequeueReusableHeaderFooterView<T: UITableViewHeaderFooterView>(ofType viewType: T.Type) -> T {
        guard
            let view = dequeueReusableHeaderFooterView(withIdentifier: viewType.defaultReuseIdentifier) as? T
        else { fatalError("Can't dequeue headerFooter of type: \(viewType)") }
        return view
    }
    
}

extension UICollectionView {
    
    func register<T: UICollectionViewCell>(_ cellClass: T.Type) {
        register(cellClass, forCellWithReuseIdentifier: cellClass.defaultReuseIdentifier)
    }
    
    func register<T: UICollectionViewCell>(_: T.Type) where T: ReusableView, T: NibLoadableView {
        let bundle = Bundle(for: T.self)
        let nib = UINib(nibName: T.nibName, bundle: bundle)
        register(nib, forCellWithReuseIdentifier: T.defaultReuseIdentifier)
    }
    
    func register<T: UICollectionViewCell>(_ cellClasses: [T.Type]) {
        cellClasses.forEach { register($0) }
    }
    
    func register<T: UICollectionReusableView>(_ viewClass: T.Type, forSupplementaryViewOfKind elementKind: String) {
        register(viewClass, forSupplementaryViewOfKind: elementKind,
                 withReuseIdentifier: viewClass.defaultReuseIdentifier)
    }
    
    func registerSupplementaryView<T: UICollectionReusableView>(_ viewClasses: [T.Type]) {
        viewClasses.forEach { registerSupplementaryView($0) }
    }
    
    func registerSupplementaryView<T: UICollectionReusableView>(_ viewClass: T.Type, forSupplementaryViewOfKind: String = UICollectionView.elementKindSupplementaryView) {
        register(viewClass,
                 forSupplementaryViewOfKind: forSupplementaryViewOfKind,
                 withReuseIdentifier: viewClass.defaultReuseIdentifier)
    }
    
    func registerHeaderView<T: UICollectionReusableView>(_ viewClass: T.Type) {
        register(viewClass, forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader,
                 withReuseIdentifier: viewClass.defaultReuseIdentifier)
    }
    
    func registerHeaderViews<T: UICollectionReusableView>(_ viewClasses: [T.Type]) {
        viewClasses.forEach { registerHeaderView($0) }
    }
    
    func registerFooterView<T: UICollectionReusableView>(_ viewClass: T.Type) {
        register(viewClass, forSupplementaryViewOfKind: UICollectionView.elementKindSectionFooter,
                 withReuseIdentifier: viewClass.defaultReuseIdentifier)
    }
    
    func registerFooterViews<T: UICollectionReusableView>(_ viewClasses: [T.Type]) {
        viewClasses.forEach { registerFooterView($0) }
    }
    
    // MARK: - Dequeue cells & views
    
    func dequeueReusableCell<T: UICollectionViewCell>(ofType cellType: T.Type, for indexPath: IndexPath) -> T {
        guard
            let cell = dequeueReusableCell(withReuseIdentifier: cellType.defaultReuseIdentifier,
                                           for: indexPath) as? T
        else { fatalError("Can't dequeue cell of type: \(cellType)") }
        return cell
    }
    
    func dequeueReusableSupplementaryView<T: UICollectionReusableView>(ofKind elementKind: String,
                                                                       viewType: T.Type,
                                                                       for indexPath: IndexPath) -> T {
        guard
            let view = dequeueReusableSupplementaryView(ofKind: elementKind,
                                                        withReuseIdentifier: viewType.defaultReuseIdentifier,
                                                        for: indexPath) as? T
        else { fatalError("Can't dequeue view of type: \(viewType)") }
        return view
    }
    
    func dequeueReusableHeaderView<T: UICollectionReusableView>(ofType viewType: T.Type,
                                                                for indexPath: IndexPath) -> T {
        return dequeueReusableSupplementaryView(ofKind: UICollectionView.elementKindSectionHeader,
                                                viewType: viewType,
                                                for: indexPath)
    }
    
    func dequeueReusableFooterView<T: UICollectionReusableView>(ofType viewType: T.Type,
                                                                for indexPath: IndexPath) -> T {
        return dequeueReusableSupplementaryView(ofKind: UICollectionView.elementKindSectionFooter,
                                                viewType: viewType,
                                                for: indexPath)
    }
}

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 :).

class BookListViewController: UIViewController, UICollectionViewDataSource {

    @IBOutlet private weak var collectionView: UICollectionView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.collectionView.register(BookCell.self)
    }

    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell: BookCell = collectionView.dequeueReusableCell(forIndexPath: indexPath)
        
        // TODO: configure cell
    
        return cell
    }
    ...
}

Conclusion

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment