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

大兔子大兔子 提交于 2019-12-04 13:30:33

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

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.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!