以快速顺序添加动画

时间:2016-07-28 19:19:54

标签: ios swift animation

Animation

我正在使用集合视图,我使用以下代码使用CATransform3DRotate为每个单元格制作动画,使用执行中的小延迟

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {

    guard let cell = collectionView.dequeueReusableCellWithReuseIdentifier("cell", forIndexPath: indexPath) as? RotationCollectionViewCell else {

        fatalError("\(String(RotationCollectionViewCell)) not found")
    }

    self.addAnimationToCells(cell)

    return cell
}

这是为单元设置动画并创建延迟的代码

func collectionView(collectionView: UICollectionView, willDisplayCell cell: UICollectionViewCell, forItemAtIndexPath indexPath: NSIndexPath) {
    self.delayTime += 0.05
    print(delayTime, "WILL DISPLAY DELAY TIME")
}

private func addAnimationToCells(cell : UICollectionViewCell) {


        let singleCell: UICollectionViewCell = cell
        let layer: CALayer = singleCell.layer

        layer.anchorPoint = CGPointMake(0.5, 0.0)

        var transform = CATransform3DIdentity;
        transform.m34 = 1.0 / 500.0;
        transform = CATransform3DRotate(transform, CGFloat(90 * M_PI / 180), 1, 0, 0)
        singleCell.layer.transform = transform

        let start:CGFloat = 90
        let end:CGFloat = 0

        let rotationAnimation: CABasicAnimation = CABasicAnimation(keyPath: "transform.rotation.x")
        rotationAnimation.fromValue = start.degreesToRadians
        rotationAnimation.toValue = end.degreesToRadians
        rotationAnimation.duration = 0.5
        rotationAnimation.repeatCount = 0
        rotationAnimation.removedOnCompletion = false
        rotationAnimation.fillMode = kCAFillModeForwards
        rotationAnimation.delegate = CoreAnimationListener {
            finished in

            singleCell.layer.transform = CATransform3DIdentity

            singleCell.layer.removeAllAnimations()
        }

        print(delayTime, "THIS IS MY DELAY TIME")

        delay(delayTime){
            cell.layer.addAnimation(rotationAnimation, forKey: "transform.rotation.x")
        }   
}

问题是如果我滚动我有一个空格。我认为是因为最后一个加载的单元格会添加一个累积延迟的动画,因此当我滚动它需要一些动画。我无法弄清楚如何避免在加载时返回最后一个单元格的时间延迟。请帮忙

1 个答案:

答案 0 :(得分:0)

as @Beyowulf评论我只需要在ViewDidAppear中将delayTime重置为0