我想检查一个视图控制器是否存在于导航堆栈中。如果它存在,我需要弹出它,否则我需要将其推送到导航堆栈。我试过以下代码。如果它不存在,则控制正在转移到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)
}
}
答案 0 :(得分: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)
}
答案 1 :(得分:0)
希望此代码适合您。
if navigationController != nil && !(navigationController?.topViewController is YOURCONTROLLER) {
for aViewController in (navigationController?.viewControllers)!
{
if aViewController is YOURCONTROLLER {
//Your controller found
}else{
//push using navigation
}
}
}
答案 2 :(得分:0)
这是另一种方法:
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)
}