iOS开发-自定义Modal转场效果

A(AViewController)通过Present方式转场到B(BViewController)

  • 通知系统使用自定义转场而不是默认转场
// AViewController.m
- (IBAction)handleNextButtonPressed:(id)sender {
    BViewController *bVC = [BViewController new];
    bVC.transitioningDelegate = self;
    bVC.modalPresentationStyle = UIModalPresentationCustom;// present之后不会移除AViewController.view,因此dismiss动画对象中不用添加toView了
    [self presentViewController:bVC animated:YES completion:^{
        
    }];
}
// AViewController.m
// 实现UIViewControllerTransitioningDelegate协议中的方法
- (id)animationControllerForPresentedController:(UIViewController *)presented presentingController:(UIViewController *)presenting sourceController:(UIViewController *)source {
    return _presentAnimation; //_presentAnimatino为实现了UIViewControllerAnimatedTransitioning协议的动画对象
}
  • 实现具体动画效果
// PresentAnimation.m
@implementation PresentAnimation

- (NSTimeInterval)transitionDuration:(id)transitionContext {
    return 0.6;
}

- (void)animateTransition:(id)transitionContext {
    UIViewController *toVC = [transitionContext viewControllerForKey:UITransitionContextToViewControllerKey];
    UIView *containerView = [transitionContext containerView];
    
    [containerView addSubview:toVC.view];
    
    CGRect targetFrame = [transitionContext finalFrameForViewController:toVC];
    toVC.view.frame = CGRectOffset(targetFrame, CGRectGetWidth(targetFrame), -CGRectGetHeight(targetFrame));
    [UIView animateWithDuration:[self transitionDuration:transitionContext] animations:^{
        toVC.view.frame = targetFrame;
    } completion:^(BOOL finished) {
        [transitionContext completeTransition:YES];
    }];
}

@end

B(BViewController)通过dismiss方式转场到A(AViewController)

  • 通知系统使用自定义转场而不是默认转场
// BViewController.m
- (IBAction)handeBackButtonPressed:(id)sender {
    self.transitioningDelegate = self;// 抢回Delegate
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
}
// BViewController.m
// 实现UIViewControllerTransitioningDelegate协议中的方法
- (nullable id )animationControllerForDismissedController:(UIViewController *)dismissed {
    return _dismissAnimation;
}
  • 实现具体动画效果
// DismissAnimation.m
@implementation DismissAnimation

- (NSTimeInterval)transitionDuration:(id)transitionContext {
    return 0.6;
}

- (void)animateTransition:(id)transitionContext {
    UIViewController *fromVC = [transitionContext viewControllerForKey:UITransitionContextFromViewControllerKey];
    
    CGRect targetFrame = [transitionContext initialFrameForViewController:fromVC];
    targetFrame = CGRectOffset(targetFrame, CGRectGetWidth(targetFrame), - CGRectGetHeight(targetFrame));
    [UIView animateWithDuration:[self transitionDuration:transitionContext] animations:^{
        fromVC.view.frame = targetFrame;
    } completion:^(BOOL finished) {
        [transitionContext completeTransition:YES];
    }];
}

@end

Demo地址

你可能感兴趣的:(iOS开发-自定义Modal转场效果)