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

时间:2017-10-22 12:30:37

标签: ios swift uiview uicollectionview uicollectionviewcell

我如何设置水平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
    }

2 个答案:

答案 0 :(得分:11)

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
    }
}

答案 1 :(得分: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)
                }
            }
        }
}