如果导航堆栈中不存在视图控制器,则推送它
Posted
技术标签:
【中文标题】如果导航堆栈中不存在视图控制器,则推送它【英文标题】:Push a viewcontroller if it is not present in the navigation stack 【发布时间】:2018-05-02 09:28:56 【问题描述】:我想检查导航堆栈中是否存在视图控制器。如果它存在,我需要弹出它,否则我需要将它推送到导航堆栈。我已经尝试了以下代码。如果它不存在,则控制正在转移到 else 块,但我无法导航到屏幕。请帮帮我
for aViewController in viewControllers!
if aViewController is TabProfileViewController
self.navigationController?.popToViewController(aViewController, animated: true)
else
let lvc = self.storyboard?.instantiateViewController(withIdentifier: "LoginViewController") as? LoginViewController
self.navigationController?.pushViewController(lvc!, animated: true)
【问题讨论】:
使用 if (aviewcontroller.isKind(of: TabProfileViewController.self)) 检查您的 aviewcontroller 【参考方案1】:你在每个循环中检查它,所以如果第一个条件是真的,它可能会在下一次迭代中变为假,所以它会弹出并推送。试试下面的代码:
if let viewController = viewControllers?.first(where: $0 is TabProfileViewController )
navigationController?.popToViewController(viewController, animated: true)
else
let lvc = storyboard?.instantiateViewController(withIdentifier: "LoginViewController") as? LoginViewController
navigationController?.pushViewController(lvc!, animated: true)
【讨论】:
【参考方案2】:希望此代码对您有用。
if navigationController != nil && !(navigationController?.topViewController is YOURCONTROLLER)
for aViewController in (navigationController?.viewControllers)!
if aViewController is YOURCONTROLLER
//Your controller found
else
//push using navigation
【讨论】:
【参考方案3】:这是另一种方法:
if arrViewController != nil && !(arrViewController?.topViewController is TabProfileViewController)
for aViewController in (arrViewController?.viewControllers)!
if aViewController is Dashboard
_ = self.navigationController?.popToViewController(aViewController, animated: true)
break
else
let lvc = self.storyboard?.instantiateViewController(withIdentifier: "LoginViewController") as? LoginViewController
self.navigationController?.pushViewController(lvc!, animated: true)
【讨论】:
以上是关于如果导航堆栈中不存在视图控制器,则推送它的主要内容,如果未能解决你的问题,请参考以下文章
Swift iOS - 如何打印导航堆栈中尚未推送的所有子视图控制器的列表
是否存在 Modal ViewController: 将视图控制器添加到堆栈中?