Shags mando
Shags mando

Reputation: 105

How to animate UICollectionview cells as i scroll

How can i animate Horizontal Collectionview as it is scrolled i changed alpha to 0 in the cell and in cellForItemAt i animate the alpha back to 1 but that only happens when the Collectionview is scrolled through the first time here is the code i have tried

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

I also tried to do this in scrollViewDidEndDecelerating but still not working

 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
    }

Upvotes: 8

Views: 11925

Answers (2)

Sébastien REMY
Sébastien REMY

Reputation: 2468

Swift 4:

Use this function from UICollectionViewDelegate:

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

Upvotes: 18

Fuad Adetoro
Fuad Adetoro

Reputation: 244

Firstly you need to know which cells are visible so set this variable at the top of the file.

var visibleIndexPath: IndexPath? = nil

In scrollViewDidEndDecelerating use this code to set the 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
    }
}

Now that you have a visibleIndexPath you can animate the cell in the willDisplay cell function.

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

Upvotes: 2

Related Questions