Table view cell load animation one after another
Swift 4
Add this little cute extension
extension UITableView {
func reloadWithAnimation() {
self.reloadData()
let tableViewHeight = self.bounds.size.height
let cells = self.visibleCells
var delayCounter = 0
for cell in cells {
cell.transform = CGAffineTransform(translationX: 0, y: tableViewHeight)
}
for cell in cells {
UIView.animate(withDuration: 1.6, delay: 0.08 * Double(delayCounter),usingSpringWithDamping: 0.6, initialSpringVelocity: 0, options: .curveEaseInOut, animations: {
cell.transform = CGAffineTransform.identity
}, completion: nil)
delayCounter += 1
}
}
}
Then, instead of "tableView.reloadData()", use "tableView.reloadWithAnimation()"
Here's my Swift 3 solution for displaying the cells one by one. what's nice about it is that they load only at first load time, and only for the initially displayed cells (will not run when user scrolls down).
Enjoy :)
private var finishedLoadingInitialTableCells = false
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
var lastInitialDisplayableCell = false
//change flag as soon as last displayable cell is being loaded (which will mean table has initially loaded)
if yourTableData.count > 0 && !finishedLoadingInitialTableCells {
if let indexPathsForVisibleRows = tableView.indexPathsForVisibleRows,
let lastIndexPath = indexPathsForVisibleRows.last, lastIndexPath.row == indexPath.row {
lastInitialDisplayableCell = true
}
}
if !finishedLoadingInitialTableCells {
if lastInitialDisplayableCell {
finishedLoadingInitialTableCells = true
}
//animates the cell as it is being displayed for the first time
cell.transform = CGAffineTransform(translationX: 0, y: self.rowHeight/2)
cell.alpha = 0
UIView.animate(withDuration: 0.5, delay: 0.05*Double(indexPath.row), options: [.curveEaseInOut], animations: {
cell.transform = CGAffineTransform(translationX: 0, y: 0)
cell.alpha = 1
}, completion: nil)
}
}