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

自闭症网瘾萝莉.ら 提交于 2020-01-13 04:55:09

问题


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:

... 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?


回答1:


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



回答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.




回答3:


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.



来源:https://stackoverflow.com/questions/25324258/how-can-i-animate-the-size-of-a-uicollectionviewcell-on-scroll-so-the-middle-one

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