A(AViewController)通過Present方式轉場到B(BViewController)
- 通知系統(tǒng)使用自定義轉場而不是默認轉場
// 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
// 實現(xiàn)UIViewControllerTransitioningDelegate協(xié)議中的方法
- (id<UIViewControllerAnimatedTransitioning>)animationControllerForPresentedController:(UIViewController *)presented presentingController:(UIViewController *)presenting sourceController:(UIViewController *)source {
return _presentAnimation; //_presentAnimatino為實現(xiàn)了UIViewControllerAnimatedTransitioning協(xié)議的動畫對象
}
- 實現(xiàn)具體動畫效果
// PresentAnimation.m
@implementation PresentAnimation
- (NSTimeInterval)transitionDuration:(id<UIViewControllerContextTransitioning>)transitionContext {
return 0.6;
}
- (void)animateTransition:(id<UIViewControllerContextTransitioning>)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)
- 通知系統(tǒng)使用自定義轉場而不是默認轉場
// BViewController.m
- (IBAction)handeBackButtonPressed:(id)sender {
self.transitioningDelegate = self;// 搶回Delegate
[self dismissViewControllerAnimated:YES completion:^{
}];
}
// BViewController.m
// 實現(xiàn)UIViewControllerTransitioningDelegate協(xié)議中的方法
- (nullable id <UIViewControllerAnimatedTransitioning>)animationControllerForDismissedController:(UIViewController *)dismissed {
return _dismissAnimation;
}
- 實現(xiàn)具體動畫效果
// DismissAnimation.m
@implementation DismissAnimation
- (NSTimeInterval)transitionDuration:(id<UIViewControllerContextTransitioning>)transitionContext {
return 0.6;
}
- (void)animateTransition:(id<UIViewControllerContextTransitioning>)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