从 UINavigationControllerDelegate 中获取当前视图控制器

3
有没有一种方法可以在转场时从内部获取正在过渡的视图控制器:
- (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated

当我使用navigationController.topViewController时,我得到的是我即将进入的视图控制器。如果我在导航系统中深入,可以使用navigationController.viewControllers(因为我可以在数组中查找上一个控制器),但如果我移动到“外部”,这种方法就不起作用了,因为我需要的视图控制器可能已经不存在了。
有没有一般的方法来解决这个问题? 我需要它,这样我就可以在动画期间添加子视图,然后当然它会消失。
谢谢
2个回答

0
我看了一下UINavigationControllerDelegate,我相信如果你尝试使用代理来实现这个功能,你将会遇到很多麻烦才能让它正常工作,而如果你使用UINavigationController的子类并重写以下方法,你可以更轻松、更干净地完成它:
- (void)pushViewController:(UIViewController *)viewController animated:(BOOL)animated;
- (UIViewController *)popViewControllerAnimated:(BOOL)animated;
and if you plan to use them 
- (NSArray *)popToViewController:(UIViewController *)viewController animated:(BOOL)animated;
and
- (NSArray *)popToRootViewControllerAnimated:(BOOL)animated;

您还需要将要添加到转换视图中的视图存储在导航控制器中作为实例变量。在本例中,我将其称为viewForTransition。

一个被覆盖方法的示例:

- (void)pushViewController:(UIViewController *)viewController animated:(BOOL)animated {
     // Submit an animation which adds the viewForTransitioning to the view about to be pushed off screen.
     // Upon completion, the animation will remove the viewForTransitioning from it's superview.
     // You also need to figure out the proper duration and delay and store them in constants or as instance variables.

     [UIView animateWithDuration:theDuration delay:theDelay options:UIViewAnimationOptionCurveLinear animations:^{
          [self.topViewController.view addSubview:self.viewForTransition];
     } completion:^{
          [self.viewForTransition removeFromSuperview];
     }];
     // after submitting the animation, call super.
     // if this makes the view appear for a few moments and then disappear before animating to the next view controller, you might try calling super after calling addSubview.
     // if that doesn't work you can try storing the old top view controller in an instance variable so that it can be accessed by the delegate when navigationController:willShowViewController:animated: is called.
     [super pushViewController:viewController animated:animated];
}

我不完全确定这会不会做你想要的事情。但是值得一试。


谢谢你的建议,最终我选择了不同的实现方式,因为之前的想法似乎是错误的。谢谢! - Idan
还有一些需要重写的方法:setViewControllers:setViewControllers:animated:showViewController:sender:。此外,还有一个interactivePopGestureRecognizer手势,它可能会交互式地弹出一个视图控制器(即使稍后被取消,它也会调用popViewControllerAnimated)。 - fabb

0
如果你想从导航控制器的数组中找到特定的视图控制器,可以尝试以下方法……
for(UIViewController * VC in [self.navigationController viewControllers])
{
    if([VC isKindOfClass:[ViewController class]])
    {
        //YOUR CODE ....... 
    }
}

享受编码......


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接