如何在UICollectionViewCell中添加动画

问题描述 投票:1回答:1

我正在尝试在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")
swift core-animation uicollectionviewcell calayer
1个回答
-1
投票

我想你可以在这个CollectionView方法中使用它。

 func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath)

并使用cell.layer更改图层

© www.soinside.com 2019 - 2024. All rights reserved.