mike vorisis
mike vorisis

Reputation: 2832

How to check if a cell has been displayed Swift

When I display my tableview I've made my cells come with an animation like this.

 func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {

             cell.alpha = 0
             let rotation = CATransform3DTranslate(CATransform3DIdentity, -250, 20, 0)
             cell.layer.transform = rotation
             UIView.animateWithDuration(0.9){
             cell.alpha = 1
             cell.layer.transform = CATransform3DIdentity

    }

It's working like this but when i go down and then up again to see the previous cells the animation still exists.

Show I believe I have to check if the cell has been displayed.

Something I try is to use didEndDisplayingCell function and put the cell.tag inside an array and then I was checking if the current cell is inside that array with array.contains(cell.tag) but it didn't work. Actually the animation worked only for the three first cells and then nothing.

Upvotes: 3

Views: 4603

Answers (3)

harpreetSingh
harpreetSingh

Reputation: 1374

what you can do is put the indexpath of cell in an array and check if the indexpath is in array.if the indexpath is in array dont perform animation

Upvotes: 1

slxl
slxl

Reputation: 689

As @James-P mentioned in comments - just create an array

var indexPathArray = [NSIndexPath]()

and rewrite your willDisplayCell method:

func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {

    if !indexPathArray.contains(indexPath) {

        indexPathArray.append(indexPath)

        cell.alpha = 0
        let rotation = CATransform3DTranslate(CATransform3DIdentity, -250, 20, 0)
        cell.layer.transform = rotation
        UIView.animateWithDuration(0.9){
            cell.alpha = 1
            cell.layer.transform = CATransform3DIdentity
        }
    }
}

Upvotes: 1

James P
James P

Reputation: 4836

You should keep an array of indexPaths, adding to it whenever a cell is displayed. This way you can check if the cell has already animated.

if (!indexPaths.contains(indexPath)) {
    indexPaths.append(indexPath)
    cell.alpha = 0
    let rotation = CATransform3DTranslate(CATransform3DIdentity, -250, 20, 0)
    cell.layer.transform = rotation
    UIView.animateWithDuration(0.9){
        cell.alpha = 1
        cell.layer.transform = CATransform3DIdentity
    }
}

Upvotes: 5

Related Questions