Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Table view cell load animation one after another

I need to animate the load of the table view rows. When the table reloads the data I need the rows get in from the left one after another. How can I achieve this?

like image 344
Andrea Mario Lufino Avatar asked Oct 29 '15 09:10

Andrea Mario Lufino


2 Answers

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()"

like image 98
Ahmadreza Avatar answered Nov 15 '22 14:11

Ahmadreza


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)
    }
}
like image 44
chikko Avatar answered Nov 15 '22 14:11

chikko