如何检查控制器是否已经在navigationcontroller视图控制器堆栈上



我得到这个错误:

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Pushing the same view controller instance more than once is not supported

如何检查堆栈中是否已经存在控制器,而不是推动该控制器,而是移动到它?

这里有一些代码,我正在根据选项卡选择推送控制器:

func tabSelected(tab: String) {
    switch tab{
    case "payment":
        mainNavigationController.popToViewController(myAccountViewController, animated: true)
    break
    case "delivery":
        mainNavigationController.pushViewController(deliveryViewController, animated: true)
        break
    case "service":
        mainNavigationController.pushViewController(serviceViewController, animated: true)
        break
    case "profile":
        mainNavigationController.pushViewController(profileViewController, animated: true)
        break
    default:
        break
    }
}

您似乎正在将同一个控制器推送到导航堆栈中。不能将视图控制器推送到堆栈中已经存在的堆栈上。可能是您多次调用tabSelected()方法,所以您应该确保它不会被多次调用。

防止崩溃的一个好方法是弹出现有的控制器,其已经在堆栈中。因此,无论何时离开视图控制器,都应该执行类似self.navigationController?.popToViewController(myViewController, animated: true)的操作。

或者,您可以执行以下操作来检查堆栈中已经存在的控制器:

 if (self.navigationController?.topViewController.isKindOfClass(ViewController) != nil) {
}

对于您的特定情况,请执行以下操作:

if(mainNavigationController.topViewController.isKindOfClass(ProfileViewController) != nil) {
    }

您可以检查导航控制器的viewControllers属性。

if contains(mainNavigationController.viewControllers, controller) {
  // move it
} else {
  // push it
}

要检查导航堆栈中是否存在视图控制器,可以使用以下方法。这将在Swift 5:中编译

    if let stack = self.navigationController?.viewControllers {
      for vc in stack where vc.isKind(of: SomeViewController.self) {
        debugPrint("exists")
      }
    }

最新更新