Uday Babariya
Uday Babariya

Reputation: 1021

UITableViewCell animation in only one direction

I want to animate UITableViewCell only in one direction [down direction]

my code:

 func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        cell.alpha = 0
         let transform = CATransform3DTranslate(CATransform3DIdentity, 0, 200 , 0)
        cell.layer.transform = transform

        UIView.animate(withDuration: 0.5, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 1, options: .curveEaseOut, animations: {
            cell.alpha = 1
            cell.layer.transform = CATransform3DIdentity
        })
    }

how can i stop that animation [don't perform animation] while user scroll upside?
thanks!!

Upvotes: 1

Views: 260

Answers (1)

Milan Nosáľ
Milan Nosáľ

Reputation: 19737

If you have just one section, you can simply compare the current indexPath with the one that was presented as last, and animate only when the new indexPath.row is greater:

fileprivate var lastIndexPath: IndexPath = IndexPath(row: -1, section: 0)

func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {

    // perform animation only when new indexPath.row is greater then the last presented
    if lastIndexPath.row < indexPath.row {
        cell.alpha = 0
        let transform = CATransform3DTranslate(CATransform3DIdentity, 0, 200 , 0)
        cell.layer.transform = transform

        UIView.animate(withDuration: 0.5, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 1, options: .curveEaseOut, animations: {
            cell.alpha = 1
            cell.layer.transform = CATransform3DIdentity
        })
    }

    lastIndexPath = indexPath
}

In case of multiple sections, the approach is the same, just the comparison would be a bit more complicated, because you will have to take sections into account. So instead of:

if lastIndexPath.row < indexPath.row {

You would have to use something like:

if lastIndexPath.section < indexPath.section ||
   (lastIndexPath.section == indexPath.section && lastIndexPath.row < indexPath.row) {

Upvotes: 1

Related Questions