如何在我滚动时为 UICollectionview 单元格设置动画

How to animate UICollectionview cells as i scroll

如何在滚动时为水平 Collectionview 设置动画我将单元格中的 alpha 更改为 0,在 cellForItemAt 中我将 alpha 设置回 1 的动画但这只会在 Collectionview 第一次滚动时发生这是我试过的代码

UIView.animate(withDuration: 0.8) {
        cell.imageView.alpha = 1
        cell.onboardLabel.alpha = 1
 }

我也在 scrollViewDidEndDecelerating 中尝试过这样做,但仍然无法正常工作

 let index = Int(scrollView.contentOffset.x) / Int(scrollView.frame.width)
 let indexPath = IndexPath(item: index, section: 0)
 let cell = collectionView.cellForItem(at: indexPath) as? OnboardingCell

    UIView.animate(withDuration: 0.8) {
        cell?.imageView.alpha = 1
        cell?.onboardLabel.alpha = 1
    }

首先你需要知道哪些单元格是可见的,所以在文件的顶部设置这个变量。

var visibleIndexPath: IndexPath? = nil

在 scrollViewDidEndDecelerating 中使用此代码设置 visibleIndexPath:

func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
    var visibleRect = CGRect()

    visibleRect.origin = collectionView.contentOffset
    visibleRect.size = collectionView.bounds.size

    let visiblePoint = CGPoint(x: visibleRect.midX, y: visibleRect.midY)

    if let visibleIndexPath = collectionView.indexPathForItem(at: visiblePoint) {
        self.visibleIndexPath = visibleIndexPath
    }
}

现在您有了 visibleIndexPath,您可以在 willDisplay 单元格函数中为单元格设置动画。

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

        if let visibleIndexPath = self.visibleIndexPath {

            // This conditional makes sure you only animate cells from the bottom and not the top, your choice to remove.
            if indexPath.row > visibleIndexPath.row {

                cell.contentView.alpha = 0.3

                cell.layer.transform = CATransform3DMakeScale(0.5, 0.5, 0.5)

                // Simple Animation 
                UIView.animate(withDuration: 0.5) {
                    cell.contentView.alpha = 1
                    cell.layer.transform = CATransform3DScale(CATransform3DIdentity, 1, 1, 1)
                }
            }
        }
}

Swift 4:

使用 UICollectionViewDelegate 中的这个函数:

 override func collectionView(_ collectionView: UICollectionView,
                             willDisplay cell: UICollectionViewCell,
                             forItemAt indexPath: IndexPath) {
    
    cell.alpha = 0
    UIView.animate(withDuration: 0.8) {
        cell.alpha = 1
    }
}