我有一个带有 Root View Controller 和两个附加 View Controller 的应用程序。出于设计原因,这些应该出现在根 VC 的左侧或右侧。这种空间关系应该以它们出现在屏幕上时呈现给用户的方式来表示。即通过推送动画。
当推送一个新的 View Controller 时,它从右边进入屏幕,这样工作正常或者我的两个 VC 之一。对于另一个,我创建了 a custom segue based on this example这将使 VC 从左到右出现。
这可行,但动画本身并不是无缝的。它看起来不像是从左侧将 View 推到根 VC 上 - 它看起来好像在 View 出现之前有一个可见的黑色背景。
我想知道是否有人知道如何获得与默认“推送”(即从右到左)动画完美镜像的动画?
最佳答案
Check out this article .它做的正是你想要的,除了过渡本身。简而言之:
1) 创建一个对象来执行动画
@interface Animator : NSObject <UIViewControllerAnimatedTransitioning>
@end
2) 成为您的导航 Controller 的委托(delegate),并在此导航 Controller 委托(delegate)方法上回答该动画师的实例:
// in your vc.m
@interface ViewController () <UINavigationControllerDelegate> // add this
// in view did load
self.navigationController.delegate = self;
// implement this to pass your animator as the thing to be in charge of the transition animation
- (id<UIViewControllerAnimatedTransitioning>)navigationController:(UINavigationController *)navigationController
animationControllerForOperation:(UINavigationControllerOperation)operation fromViewController:(UIViewController*)fromVC toViewController:(UIViewController*)toVC {
if (operation == UINavigationControllerOperationPush) {
return [[Animator alloc] init];
}
return nil;
}
3) 在你的动画师中,回答持续时间:
- (NSTimeInterval)transitionDuration:(id <UIViewControllerContextTransitioning>)transitionContext
{
return 0.25;
}
4) 所有这些都来自这篇文章。剩下要做的唯一一件事就是实现从左到右的滑动。 (我更改了文章的代码来执行从左到右的幻灯片):
- (void)animateTransition:(id<UIViewControllerContextTransitioning>)transitionContext
{
UIViewController* toViewController = [transitionContext viewControllerForKey:UITransitionContextToViewControllerKey];
UIViewController* fromViewController = [transitionContext viewControllerForKey:UITransitionContextFromViewControllerKey];
CGRect fromVCFrame = fromViewController.view.frame;
CGFloat width = toViewController.view.frame.size.width;
[[transitionContext containerView] addSubview:toViewController.view];
toViewController.view.frame = CGRectOffset(fromVCFrame, -width, 0);
[UIView animateWithDuration:[self transitionDuration:transitionContext] animations:^{
fromViewController.view.frame = CGRectOffset(fromVCFrame, width, 0);
toViewController.view.frame = fromVCFrame;
} completion:^(BOOL finished) {
fromViewController.view.frame = fromVCFrame;
[transitionContext completeTransition:![transitionContext transitionWasCancelled]];
}];
}
我在一个小项目中尝试了所有这些,效果非常好。
关于ios - 推送 View Controller 时无缝动画 "from left to right"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23877994/