Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How Can I Animate the Size of A UICollectionViewCell on Scroll so the middle one is largest?

I have a UICollectionView that shows several rows with one, full-width column (looks like a UITableView)

What I'd like to achieve is something similar to this:

UICollectionView with animations

... where the middle cell has a much greater height. As the user scrolls up and down, the cells before and after the middle cell animate back to the default height for the given cell.

Can somebody outline how I should approach this problem?

like image 945
bodacious Avatar asked Dec 26 '22 05:12

bodacious


1 Answers

I use this Swift 3 code in my horizontal UICollectionView.

func scrollViewDidScroll(_ scrollView: UIScrollView) {
    let centerX = scrollView.contentOffset.x + scrollView.frame.size.width/2
    for cell in mainCollectionView.visibleCells {

        var offsetX = centerX - cell.center.x
        if offsetX < 0 {
            offsetX *= -1
        }

        cell.transform = CGAffineTransform(scaleX: 1, y: 1)
        if offsetX > 50 {

            let offsetPercentage = (offsetX - 50) / view.bounds.width
            var scaleX = 1-offsetPercentage

            if scaleX < 0.8 {
                scaleX = 0.8
            }
            cell.transform = CGAffineTransform(scaleX: scaleX, y: scaleX)
        }
    }
}
like image 119
Roland Keesom Avatar answered Jan 30 '23 23:01

Roland Keesom