Tiago Pereira
Tiago Pereira

Reputation: 592

Custom animation in UICollectionViewFlowLayout - scroll direction horizontal

I am implementing a custom UICollectionViewFlowLayout and I would like to do something like this:

enter image description here

Basically, this is a simple collection view with the scroll direction set as UICollectionViewScrollDirectionHorizontal.

The active cell A (cell in the middle) must have a fixed size (ex: 300x300) and the other cells, in this case B, should be smaller (ex: 275x275).

When the scroll is performed between them, both cells should transform their size.

I probably need to override the - (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect and implement some kind of CGAffineTransformMakeScale. Am I thinking right? Anyone else did this before?

Upvotes: 0

Views: 1104

Answers (1)

Tiago Pereira
Tiago Pereira

Reputation: 592

Problem solved.

- (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect
{
    CGFloat centerX = self.collectionView.contentOffset.x + self.collectionView.frame.size.width * 0.5;

    NSArray *attributes = [super layoutAttributesForElementsInRect:rect];

    for (UICollectionViewLayoutAttributes *attrs in attributes) {

        CGFloat diff = ABS(attrs.center.x - centerX);

        CGFloat newScale = diff * scaleFactor / (self.itemSize.width + self.minimumLineSpacing);

        if (newScale > scaleFactor) {
            newScale = scaleFactor;
        }

        attrs.transform = CGAffineTransformMakeScale(1 - newScale, 1 - newScale);
    }

    return attributes;
}

Upvotes: 2

Related Questions