我正在修改这个使用动态动画器进行视图控制器转换的示例。我想做的一件事是让它在 iPad 上工作,并改变重力从上到下到右到左的过渡方向。如果有一种方法可以让我根据视图大小、施加的力和重力方向来计算视图转换的时间,我很感兴趣?换句话说,视图到达右边界并停止反弹需要多长时间。
我想从以下位置返回这个正确的持续时间:
- (NSTimeInterval)transitionDuration:(id<UIViewControllerContextTransitioning>)transitionContext
我正在使用的示例将推送幅度设置为 100,这适用于 iPhone 屏幕,但对于 iPad 屏幕来说“太慢”。据我了解,力会施加到屏幕尺寸上,iPad 屏幕需要更强的推动力才能及时移动。
所以我修改了代码如下:
pushBehavior.pushDirection = CGVectorMake(1,0);
pushBehavior.magnitude = 700.0;
UIGravityBehavior *gravityBehavior = [[UIGravityBehavior alloc] initWithItems:@[toViewController.view]];
gravityBehavior.gravityDirection = CGVectorMake(-1.0, 0);
哪个有效,但现在我不知道新的过渡需要多长时间。默认值是 1.5 秒,这是可行的,但如果我将其设置为 0.7 秒,视图会在过渡过程中卡住。
- (NSTimeInterval)transitionDuration:(id<UIViewControllerContextTransitioning>)transitionContext {
return 1.5f;
}
- (UIDynamicAnimator*)animateForTransitionContext:(id<UIViewControllerContextTransitioning>)transitionContext {
// Get the view controllers for the transition
UIViewController *fromViewController = [transitionContext viewControllerForKey:UITransitionContextFromViewControllerKey];
UIViewController *toViewController = [transitionContext viewControllerForKey:UITransitionContextToViewControllerKey];
// Prepare the view of the toViewController
toViewController.view.frame = CGRectOffset(fromViewController.view.frame, 1.0f*fromViewController.view.frame.size.width,0);
// Add the view of the toViewController to the containerView
[[transitionContext containerView] addSubview:toViewController.view];
// Create animator
UIDynamicAnimator *animator = [[UIDynamicAnimator alloc] initWithReferenceView:[transitionContext containerView]];
// Add behaviors
UIGravityBehavior *gravityBehavior = [[UIGravityBehavior alloc] initWithItems:@[toViewController.view]];
gravityBehavior.gravityDirection = CGVectorMake(-1.0, 0);
UICollisionBehavior *collisionBehavior = [[UICollisionBehavior alloc] initWithItems:@[toViewController.view]];
[collisionBehavior addBoundaryWithIdentifier:@"LeftBoundary" fromPoint:CGPointMake(0,0) toPoint:CGPointMake(0.0f, fromViewController.view.frame.size.height+1)];
UIDynamicItemBehavior *propertiesBehavior = [[UIDynamicItemBehavior alloc] initWithItems:@[toViewController.view]];
propertiesBehavior.elasticity = 0.2;
UIPushBehavior *pushBehavior = [[UIPushBehavior alloc] initWithItems:@[toViewController.view] mode:UIPushBehaviorModeInstantaneous];
// pushBehavior.angle = 0;
pushBehavior.pushDirection = CGVectorMake(-1, 0);
pushBehavior.magnitude = 700.0;
[animator addBehavior:pushBehavior];
[animator addBehavior:propertiesBehavior];
[animator addBehavior:collisionBehavior];
[animator addBehavior:gravityBehavior];
return animator;
}