iOS 9 上带有 NavigationController 的推送动画的自定义过渡

Custom transition for push animation with NavigationController on iOS 9

我有一个嵌入在 UINavigationController 中的视图控制器之间的自定义推送转换,它在使用 iOS 7/8 构建时工作正常,但在针对 iOS 构建时呈现错误的布局9 SDK.

- (void)animateTransition:(id<UIViewControllerContextTransitioning>)transitionContext
{
  UIViewController *fromViewController = [transitionContext viewControllerForKey:UITransitionContextFromViewControllerKey];
  UIViewController *toViewController = [transitionContext viewControllerForKey:UITransitionContextToViewControllerKey];

  [transitionContext.containerView addSubview:toViewController.view];

  ...

然后它继续执行动画。问题是 toViewController 的内容,即使它使用右上布局指南自动布局约束,也会显示导航栏后面的内容。

然而,它在 iOS 8 上运行良好,如果我们强制重绘(例如,将应用程序发送到后台并将其返回,在顶部显示模态并关闭它等)将导致整个自动布局系统重绘自身并且 toViewController 的视图跳转到正确的位置(作为顶部布局指南,导航栏的 x 像素而不是设备屏幕顶部的 x 像素)。

添加

[self.view setNeedsUpdateConstraints];
[self.view layoutIfNeeded];

如果放在 viewDidAppear:animated 中有效,但在 viewDidLoadviewWillAppear:animated 中无效。这不是解决方案,因为当重绘发生在 viewDidAppear:animated

时,用户会看到视图跳跃

我已通过在 addSubview: 之前添加以下行来解决我的问题:

  toViewController.view.frame = [transitionContext finalFrameForViewController:toViewController];

来自 finalFrameForViewController:

的 Apple 文档

Returns the ending frame rectangle for the specified view controller’s view.

The rectangle returned by this method represents the size of the corresponding view at the end of the transition. For the view being covered during the presentation, the value returned by this method might be CGRectZero but it might also be a valid frame rectangle.