4

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?

bodacious
  • 6,282
  • 8
  • 39
  • 67

3 Answers3

9

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)
        }
    }
}
Roland Keesom
  • 7,860
  • 5
  • 42
  • 50
2

You need to create a custom subclass of UICollectionViewLayout.

First of all, override - (BOOL)shouldInvalidateLayoutForBoundsChange:(CGRect)newBounds to return yes, that way, you can change the layout attributes of your cells as your collection is being scrolled.

After that, your key methods to override are:

- (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect

and

- (UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath

I suggest reading an article about custom collection view layouts. It can be pretty heavy subject matter.

daltonclaybrook
  • 6,099
  • 1
  • 28
  • 37
-1

since the UICollectionView is the subclass of UIScrollView, you can solved this problem by treating your collectionView as a scrollView.
set the UIScrollViewDelegate and implemented scrollViewDidScroll, and then do something like this:

-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    for (int i = 0; i < [scrollView.subviews count]; i++) {
        UIView *cell = [scrollView.subviews objectAtIndex:i];
        float position = cell.center.y - scrollView.contentOffset.y;
        float offset = 1.5 - (fabs(scrollView.center.y - position) * 1.0) / scrollView.center.y;
        if (offset<1.0)
        {
            offset=1.0;
        }
        cell.transform = CGAffineTransformIdentity;
        cell.transform = CGAffineTransformScale(cell.transform, offset, offset);
    }
}

hope this will solve your problem.

leolu
  • 1