首页 > 解决方案 > 如何在 UICollectionViewCell 中添加动画

问题描述

我正在尝试在 UICollectionViewCell 内添加循环加载动画。我已将完全相同的代码添加到普通的 UIViewController 中,并且它运行成功,但我在 UICollectionViewCell 上没有得到任何结果。

理想情况下,我希望在单元格可见时开始动画。

let shapeLayer = CAShapeLayer()
let trackLayer = CAShapeLayer()

func setupBezierPaths() {
    let center = self.center
    let circularPath = UIBezierPath(arcCenter: center, radius: 100, startAngle: -CGFloat.pi / 2, endAngle: 2 * CGFloat.pi, clockwise: true)

    // Create a track layer
    trackLayer.path = circularPath.cgPath
    trackLayer.strokeColor = UIColor.lightGray.cgColor
    trackLayer.lineWidth = 10
    trackLayer.lineCap = CAShapeLayerLineCap.round
    trackLayer.fillColor = UIColor.clear.cgColor

    layer.addSublayer(trackLayer)

    // Create a layer that is animated
    shapeLayer.path = circularPath.cgPath
    shapeLayer.strokeColor = UIColor.green.cgColor
    shapeLayer.lineWidth = 10
    shapeLayer.strokeEnd = 0
    shapeLayer.lineCap = CAShapeLayerLineCap.round
    shapeLayer.fillColor = UIColor.clear.cgColor

    layer.addSublayer(shapeLayer)
}

对于 UICollectionViewCell,我不确定将实际动画代码放在哪里。我已经在 init 中尝试过,但轨道层甚至没有出现。这是动画的代码:

    let basicAnimation = CABasicAnimation(keyPath: "strokeEnd")
    basicAnimation.toValue = 1
    basicAnimation.duration = 1
    basicAnimation.fillMode = CAMediaTimingFillMode.forwards
    basicAnimation.isRemovedOnCompletion = false
    shapeLayer.add(basicAnimation, forKey: "simpleAnimation")

标签: swiftcore-animationuicollectionviewcellcalayer

解决方案


推荐阅读