The UITableViewCell's swift extension of UITableViewCellLifecycleExtension
(with MDTableViewDelegate
) provide lifecycle events for UITableViewCell, just like similar events of UIViewController:
- cellWillAppear
- cellDidAppear
- cellDidLayoutSubviews
- cellDidDisappear
I'm a big fan of UITableView, since it provides the flexibility of organizing contents dynamically. And with more and more animations in the UI, I found it hard to locate my code elegantly.
On the other hand, UIViewController is nice with viewWillAppear, viewDidAppear, viewDidLayoutSubviews, viewWillDisappear and viewDidDisappear etc.
I though I shall make this happen to UITableViewCell.
see the sample code
- Include
UITableViewCellLifecycleExtension.swift
andMDTableViewDelegate.swift
into the projects. Subclass MDTableViewDelegate, and put your tableView's dataSource and delegate code in this class. And these events will be triggerred in the cells. - IMPORTANT Be sure to call
super.tableView(tableView, willDisplayCell: cell, forRowAtIndexPath: indexPath)
when implementing an override version oftableView:willDisplayCell:forRowAtIndexPath
in your subclass of MDTableViewDelegate - If UITableViewController's cells want to have these events, when impelementing the delegate within the table view controller, please refer to the implementation of
UITableViewController+Lifecycle.h/m
in the Objective-C version (see below) andMDTableViewDelegate.swift
The difference between Objective-C version and Swift version is:
the Objective-C version swizzle method `tableView:willDisplayCell:forRowAtIndexPath:` in all the subclass of `MDTableViewDelegate`, not `MDTableViewDelegate` itself.
By doing this, there is not need to call `super.tableView(tableView, willDisplayCell: cell, forRowAtIndexPath: indexPath)`, and all the hacking details are hidden.
These events won't be triggerred if the whole tableView is going on-screen or off-screen, e.g. when pushing another view controller or poped back from another view controller. (Currently I don't see the need to fix this.)
It only happens when the UITableViewCell is scrolling into or out-of the visible area of the table view.