Swift 2 - performBatchUpdates - Animate cell one b

2019-04-14 17:31发布

问题:

I am trying to animate each cell of my UICollectionView visibile in the frame. Every time I scroll a new cell appears with the animation.

I am doing this using performBatchUpdates inside cellForItemAtIndexPath however, the animation is applied to all cells at the same time and its very fast. It seems that the animation of 1 second its not recognised.

Also I am trying to find the way to apply an animation to a cell when a button is pressed with no success.

The code I use is:

override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell
{
    let Cell = collectionView.dequeueReusableCellWithReuseIdentifier("Cell", forIndexPath: indexPath) as! CellClass

    self.collectionView?.performBatchUpdates({
                        Cell.layer.cornerRadius = 200
                        return
                        }){
                            completed in

                            UIView.animateWithDuration(1, animations: {
                                Cell.layer.cornerRadius = 0
                            })
                        }

    Cell.playAnimationBtn.layer.setValue(indexPath.row, forKey: "indexPlayBtn")
}

@IBAction func actionGetAnimation(sender: UIButton)
{
    let indexUser = (sender.layer.valueForKey("indexPlayBtn")) as! Int

    //Cell selected do animation corners = 200
}

回答1:

You can make this work when you move the animation to willDisplayCell(_:cell:indexPath:). That method is called every time a new cell is about to be displayed.

You cannot use UIView.animateWithDuration for the layer properties. You have to use CABasicAnimation for that.

If you want to animate the cell when the user presses a button you can call animateCellAtIndexPath from the code example below. You have to know the cell's indexPath to do so. In this example I call this method when the user selects the cell.

func collectionView(collectionView: UICollectionView, willDisplayCell cell: UICollectionViewCell, forItemAtIndexPath indexPath: NSIndexPath) {
    animateCell(cell)
}

func animateCell(cell: UICollectionViewCell) {
    let animation = CABasicAnimation(keyPath: "cornerRadius")
    animation.fromValue = 200
    cell.layer.cornerRadius = 0
    animation.toValue = 0
    animation.duration = 1
    cell.layer.addAnimation(animation, forKey: animation.keyPath)
}

func animateCellAtIndexPath(indexPath: NSIndexPath) {
    guard let cell = collectionView.cellForItemAtIndexPath(indexPath) else { return }
    animateCell(cell)
}

func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
    animateCellAtIndexPath(indexPath)
}