如何在呈现子视图控制器时弹回子视图控制器的UICollectionView?

时间:2014-01-09 14:51:21

标签: ios animation ios7 uikit

我希望通过从顶部到底部放置子视图控制器来呈现它。子视图控制器是一个UICollectionViewController,其中包含几个单元格。我可以使用iOS7 UIViewControllerContextTransitioning进行下拉视图控制器转换。但是如果我想要在呈现子视图控制器时只收集集合视图(就像在地面上击球一样),我该怎么办?

我尝试使用UIKit Dynamics并在转换后在UICollectionView上创建一些UIAnimatorBehavior,比如UIGravityBehavior和UIPushBehavior。但它们似乎不起作用。也许我以错误的方式使用它们。有人能给我一些提示吗?

illustration of view controllers

更新

在尝试了几个解决方案之后,我终于找到了一个非常接近我想要的解决方案。该视频显示了结果:http://youtu.be/tueXDBMsdt0

但我认为应该有更好的解决方案。这是我的解决方案的步骤:

  1. 创建一个UIViewControllerAnimatedTransitioning对象,从上到下为视图控制器转换设置动画。

  2. 子视图控制器是UICollectionViewController。在转换动画结束时,我将子视图控制器的scrollview内容偏移设置为(0,-30),然后完成转换。

  3. 在子视图控制器的viewDidAppear中,将内容偏移设置为(0,0)。

  4. 此外,我还按照文章中的说明:http://www.teehanlax.com/blog/implementing-a-bouncy-uicollectionviewlayout-with-uikit-dynamics/在单元格中设置UIKit动力学动画师。当内容偏移量发生变化时,单元格看起来就像弹跳一样。

  5. 过渡动画代码如下所示:

    - (void) animateTransition:(id<UIViewControllerContextTransitioning>)transitionContext {
      UIViewController *fromViewController = [transitionContext viewControllerForKey:UITransitionContextFromViewControllerKey];
      UIViewController *toViewController = [transitionContext viewControllerForKey:UITransitionContextToViewControllerKey];
    
      CGRect frame = [[transitionContext containerView] frame];
      CGRect startFrame = frame;
      startFrame.origin.y -= CGRectGetHeight(transitionContext.containerView.frame);
    
      [transitionContext.containerView addSubview:fromViewController.view];
      [transitionContext.containerView addSubview:toViewController.view];
      toViewController.view.frame = startFrame;
    
      [UIView animateWithDuration:0.4 delay:0 options:UIViewAnimationOptionCurveEaseIn animations:^{
    
                     toViewController.view.frame = frame;
                   }
                   completion:^(BOOL finished) {
                     ((UICollectionViewController*)toViewController).contentOffset = CGPointMake(0, -30);
                     [transitionContext completeTransition:YES];
                   }];
    }
    

    在子视图控制器viewDidAppear中:

    - (void) viewDidAppear:(BOOL)animated {
      [super viewDidAppear:animated];
    
      [self.collectionView setContentOffset:CGPointMake(0, 0) animated:YES];
    }
    

    但我仍然希望细胞更自然地反弹。还有其他更好的解决方案吗?

1 个答案:

答案 0 :(得分:2)

重要提示:现在可以在iOS中使用一行简单的代码完成此操作:

https://stackoverflow.com/a/23514653/294884

需要更全面控制时的详细答案:


如果你想在iPhone上的屏幕锁定和相机之间产生相同的效果,你可以使用UIViewControllerContextTransitioning

enter image description here

这里有一个很好的教程http://www.objc.io/issue-5/view-controller-transitions.html 在这里http://www.teehanlax.com/blog/custom-uiviewcontroller-transitions/

如果您有Apple开发者帐户,则会有一个关于View控制器转换的视频:https://developer.apple.com/tech-talks/videos/

该视频被命名为“构建现代应用程序,第1部分”

这种方式仅适用于iOS7!

相关问题