如何使用Swift为UICollectionViewCells设置动画?

时间:2018-10-23 06:30:17

标签: swift uicollectionview

我目前正在尝试使我的单元一次进入故事板动画。

override func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
    cell.alpha = 0
    cell.layer.transform = CATransform3DMakeScale(0.5, 0.5, 0.5)
    UIView.animate(withDuration: 1.0, animations: { () -> Void in
        cell.alpha = 1
        cell.layer.transform = CATransform3DScale(CATransform3DIdentity, 1, 1, 1)
    })
}

这是我当前正在使用的代码。但是,它只允许我一次在所有单元上运行动画。我想要的是让单元1、2、3和4以此顺序进行动画处理。 关于如何解决这个问题有什么想法吗? 如果有更好的方法,请告诉我是否有。

3 个答案:

答案 0 :(得分:0)

您可以使用重复和自动反转选项。

UIView.animate(withDuration: 2.0, delay: 0, options: [.repeat, .autoreverse], animations: {
  cell.alpha = 1
        cell.layer.transform = CATransform3DScale(CATransform3DIdentity, 1, 1, 1)

}, completion: nil)

答案 1 :(得分:0)

我建议您使用顺序动画创建一些视图,并且仅使用UIView而不使用UICollectionView。动画制作完成后,您可以显示真实的UICollectionView。

答案 2 :(得分:0)

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

    cell.alpha = 0
    cell.layer.transform = CATransform3DMakeRotation(10, 1, 1, 0)
    UIView.animate(withDuration: 1.0, delay: 1.0*Double(indexPath.row),animations: { () -> Void in
    cell.alpha = 1

        cell.layer.transform = CATransform3DScale(CATransform3DIdentity, 1, 1, 1)
    })
}

添加后

 delay: 1.0*Double(indexPath.row)

它解决了我的问题,现在视图将它们按顺序进行了动画处理。 @Syed Faraz Haider Zaidi