如何检查视图控制器是模态显示还是在导航堆栈上推送?

问题描述 投票:114回答:15

如何在我的视图控制器代码中区分:

  • 以模态表示
  • 在导航堆栈上按下

在两种情况下,presentingViewControllerisMovingToParentViewController都为YES,所以不是很有帮助。

使事情变得复杂的是,我的父视图控制器有时是模态的,要在其上推送要检查的视图控制器。

事实证明,我的问题是我将HtmlViewController嵌入到UINavigationController中,然后显示。这就是为什么我自己的尝试和下面的好答案都无效的原因。

HtmlViewController*     termsViewController = [[HtmlViewController alloc] initWithDictionary:dictionary];
UINavigationController* modalViewController;

modalViewController = [[UINavigationController alloc] initWithRootViewController:termsViewController];
modalViewController.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
[self presentViewController:modalViewController
                   animated:YES
                 completion:nil];

我想我最好告诉我的视图控制器何时是模态的,而不是试图确定。

我如何在我的视图控制器代码中区分:在导航堆栈上以模态形式推送的presented presentingViewController和isMovingToParentViewController在这两种情况下均为YES,所以...

ios objective-c swift uiviewcontroller uinavigationcontroller
15个回答
124
投票

带着一粒盐,没经过测试。


2
投票

要检测是否已推送控制器,请在您需要的任何位置使用以下代码:


1
投票

[self.navigationController != nil表示它在导航堆栈中。


1
投票
if let navigationController = self.navigationController, navigationController.isBeingPresented {
    // being presented
}else{
    // being pushed
}

0
投票

如果您使用的是ios 5.0或更高版本,请使用此代码


-1
投票
id presentedController = self.navigationController.modalViewController;
if (presentedController) {
     // Some view is Presented
} else {
     // Some view is Pushed
}

-1
投票

对于某些想知道的人,如何告诉ViewController它正在被呈现


78
投票

Swift


74
投票

您忽略了一种方法:isBeingPresented


28
投票

Swift 5


26
投票

self.navigationController!= nil表示它在导航中堆栈。


12
投票

Swift 4


5
投票

Swift 5。


3
投票

正如许多人所建议的那样,“检查”方法不适用于所有情况,在我的项目中,我提出了手动进行管理的解决方案。关键是,我们通常自己管理演示文稿-这不是幕后发生的事情,我们必须进行内省。


3
投票

假设您以模态形式呈现的所有viewController都包装在新的navigationController中(无论如何您都应该这样做),可以将此属性添加到VC。

© www.soinside.com 2019 - 2024. All rights reserved.