Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UICollectionViewCell scale cell size while scrolling

I'm trying to create a UICollectionView where the UICollectionViewCell is getting scaled down when "leaving" the visible area at the top or bottom. And getting scaled up to normal size while "entering" the visible area.

I've been trying some scale/animation code in: scrollViewDidScroll() , but I can't seem to get it right.

My complete function looks like this:

 func scrollViewDidScroll(scrollView: UIScrollView) {

    var arr = colView.indexPathsForVisibleItems()

    for indexPath in arr{

        var cell = colView.cellForItemAtIndexPath(indexPath as! NSIndexPath)!
        var pos = colView.convertRect(cell.frame, toView: self.view)

        if pos.origin.y < 50 && pos.origin.y >= 0{

            cell.hidden = false

            UIView.animateWithDuration(0.5, animations: { () -> Void in

                cell.transform = CGAffineTransformMakeScale(0.02 * pos.origin.y, 0.02 * pos.origin.y)

            })

        }else if pos.origin.y == 50{

            UIView.animateWithDuration(0.5, animations: { () -> Void in

                cell.transform = CGAffineTransformMakeScale(1, 1)
            })

        }
    }
}

Is this in some way the right approach, or is there another better way?

like image 845
Kvarken Avatar asked May 05 '15 21:05

Kvarken


1 Answers

Not a complete solution, but a few remarks/pointers:

  1. You should not mess with the collection view cells directly in this way, but rather have a custom UICollectionViewLayout subclass that modifies the UICollectionViewLayoutAttributes to include the desired transform and invalidating the layout whenever necessary.

  2. Doing if pos.origin.y == 50 is definitely not a good idea, because the scrolling might not pass by all values (that is, it might jump from 45 to 53). So, use >= and include some other way if you want to ensure that your animation is only executed once at the "boundary" (for example, store the last position or a flag).

like image 86
Daniel Rinser Avatar answered Oct 22 '22 00:10

Daniel Rinser