如何使用animateWithDuration:在iOS 7上呈现视图控制器?

时间:2014-04-08 12:38:13

标签: ios ios7 core-animation

我目前正在使用以下代码来展示我的视图控制器。

CATransition* transition = [CATransition animation];
transition.duration = 1;
transition.type = kCATransitionFade;
transition.subtype = kCATransitionFromBottom;
[self.view.window.layer addAnimation:transition forKey:kCATransition];
[self presentViewController:viewController animated:NO completion:nil];

我需要使用UIView animateWithDuration方法来使用更复杂的动画。它只是模态演示和背景视图控制器应该留在那里。如何为呈现视图控制器的视图设置动画?

更新:下一版代码:)

UIStoryboard *sb = [UIStoryboard storyboardWithName:@"Main" bundle:NULL];
RootViewControllerEx *viewController = (RootViewControllerEx *)[sb instantiateViewControllerWithIdentifier:@"SB_RDVC"];
viewController.transitioningDelegate = self;
viewController.modalPresentationStyle = UIModalPresentationCustom;
[self presentViewController:viewController animated:YES completion:nil];
...

- (void)animateTransition:(id<UIViewControllerContextTransitioning>)transitionContext
{
    ...
}
故事板中的VC没有指定任何se​​gue,它在故事板中保持孤独:)

1 个答案:

答案 0 :(得分:5)

您需要使用UIModalPresentationCustom作为UIViewController's modalPresentationStyle

然后,您需要创建一个符合UIViewControllerTransitioningDelegate的类,并将其设置为presentedViewController

实施例

YourViewController *viewController = [[YourViewController alloc] init];
viewController.delegate = self;
viewController.transitioningDelegate = self;
viewController.modalPresentationStyle = UIModalPresentationCustom;

[self.navigationController presentViewController:viewController animated:YES completion:nil];

然后必须实现以下方法:

- (id<UIViewControllerAnimatedTransitioning>)animationControllerForPresentedController:(UIViewController *)presented presentingController:(UIViewController *)presenting sourceController:(UIViewController *)source;

返回符合UIViewControllerAnimatedTransitioning协议的对象,该协议实现以下方法:

- (void)animateTransition:(id<UIViewControllerContextTransitioning>)transitionContext
{
    UIView *inView = [transitionContext containerView];
    UIView *toView = [[transitionContext viewControllerForKey:UITransitionContextToViewControllerKey] view];

    toView.frame = //CGRectMake(0,0,0,0);
    [inView addSubview:toView];
    // Use whatever animateWithDuration you need
    [UIView animateWithDuration:0.6f delay:0.0f usingSpringWithDamping:0.7f initialSpringVelocity:0.5f options:UIViewAnimationOptionCurveEaseIn animations:^{
// Custom animation here
    } completion:^(BOOL finished) {
        // IMPORTANT
        [transitionContext completeTransition:YES];
    }];
}

始终记得在转换完成时告诉上下文,否则您将进入不稳定状态。