视图显示:如何确定视图控制器是弹出还是显示子视图控制器?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (2)
  • 关注 (0)
  • 查看 (36)

在视图控制器的-viewWillDisappear:方法,我需要找到一种方法来确定它是因为视图控制器被推到导航控制器的堆栈上,还是因为视图控制器由于弹出而消失了。

现在我正在设置像isShowingChildViewController但事情变得相当复杂。我认为我能察觉到的唯一方法是-dealloc方法。

提问于
用户回答回答于

您可以使用以下内容。

- (void)viewWillDisappear:(BOOL)animated {
  [super viewWillDisappear:animated];
  NSArray *viewControllers = self.navigationController.viewControllers;
  if (viewControllers.count > 1 && [viewControllers objectAtIndex:viewControllers.count-2] == self) {
    // View is disappearing because a new view controller was pushed onto the stack
    NSLog(@"New view controller was pushed");
  } else if ([viewControllers indexOfObject:self] == NSNotFound) {
    // View is disappearing because it was popped from the stack
    NSLog(@"View controller was popped");
  }
}

当然,这是可能的,因为UINavigationController的视图控制器堆栈(通过viewControlers属性公开)已经在viewWillDisplay被调用时更新。

用户回答回答于

我认为最简单的方法是:

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    if ([self isMovingFromParentViewController])
    {
        NSLog(@"View controller was popped");
    }
    else
    {
        NSLog(@"New view controller was pushed");
    }
}

Swift:

override func viewWillDisappear(animated: Bool)
{
    super.viewWillDisappear(animated)
    if isMovingFromParentViewController
    {
        print("View controller was popped")
    }
    else
    {
        print("New view controller was pushed")
    }
}

扫码关注云+社区