Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom animation when switching from one UICollectionViewLayout to another?

As a test I made one layout that displays cells in a vertical line and another that displays them in a horizontal layout. When I call [collectionView setCollectionViewLayout:layout animated:YES]; it animates between the two positions very cleanly.

Now that I'd like to do is have all the views do a few spins, warps and flips around the screen (probably using CAKeyframeAnimations) before finally arriving at their destination, but I can't find a good place to hook this in.

I tried subclassing UICollectionViewLayoutAttributes to contain an animation property, then setting those animations in an overridden applyLayoutAttributes: method of the UICollectionViewCell I'm using. This works... EXCEPT it appears to happen only after the layout transition is complete. If I wanted to use this, I'd have to have the layout not change the current positions of the objects right away, only after the it reaches this apply attributes part of the code, and that seems like a lot of work...

Or I could subclass UICollectionView and override setCollectionViewLayout:animated:, but that also seems like a lot of state to keep around between layouts. Neither of these optins seems right, because there's such an easy way to animate additions/deletions of cells within a layout. I feel like there should be something similar for hooking into the animations between layouts.

Does anyone know the best way to get what I'm looking to accomplish?

like image 781
Mason Cloud Avatar asked Feb 14 '13 00:02

Mason Cloud


1 Answers

#define degreesToRadians(x) (M_PI * (x) / 180.0)

UICollectionView *collectionView = self.viewController.collectionView;
HorizontalCollectionViewLayout *horizontalLayout = [HorizontalCollectionViewLayout new];
NSTimeInterval duration = 2;


[collectionView.visibleCells enumerateObjectsUsingBlock:^(UICollectionViewCell *cell, NSUInteger index, BOOL *stop)
 {
     CABasicAnimation *rotationAnimation;
     rotationAnimation = [CABasicAnimation animationWithKeyPath:@"transform.rotation"];
     rotationAnimation.toValue = @(degreesToRadians(360));
     rotationAnimation.duration = duration;
     rotationAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];

     [cell.layer addAnimation:rotationAnimation forKey:@"rotationAnimation"];
 }];

[UIView animateWithDuration:duration
                 animations:^
 {
     collectionView.collectionViewLayout = horizontalLayout;
 }];
like image 185
Zelko Avatar answered Oct 06 '22 18:10

Zelko