我正在将ViewController插入到当前堆栈中。并试图像这样执行popviewcontroller。
var viewControllersArray: [UIViewController] = self.navigationController!.viewControllers
if(dm.isLoginViewLoaded)
{
print("Login view already loaded")
}
else
{
print("Login view havent load before")
let myviewcontroller:LoginViewController=UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "LOGIN") as! LoginViewController
let index=viewControllersArray.count-2
viewControllersArray.insert(myviewcontroller, at: index)
// update navigationController viewControllers
self.navigationController!.setViewControllers(viewControllersArray, animated:false)
}
self.navigationController?.popViewController(animated: true)
但为什么我无法实现我想做的事情。即使在满足我的viewcontroller的第二个条件下总是推送到Root viewcontroller。我想在我当前的视图控制器和根视图控制器之间添加一个新的viewcontroller,并执行pop操作。请帮我。 感谢
答案 0 :(得分:0)
试试这段代码:
let arrController:[UIViewController] = (self.navigationController?.viewControllers)!//array of all controllers in navigation stack
for vc in arrController
{
if (type(of: vc) == type(of: LoginViewController
))//check exist or not
{
self.navigationController?.popToViewController((arrController[(arrController.index(of: vc))!]), animated: true)
}
}
答案 1 :(得分:0)
我认为你只是“错误地计算”阵列位置。你的索引应该是:
let index = viewControllersArray.count - 1 // *not* -2
然而,这可能是一种更“强大”的方法:
@IBAction func popToLogin(_ sender: Any) {
if let navVC = self.navigationController {
var bFoundLogin = false
var viewControllersArray = navVC.viewControllers
for vc in viewControllersArray.reversed() {
if vc is LoginViewController {
// we found LoginViewController in stack, so
// pop to it (even if it's multiple levels back)
bFoundLogin = true
navVC.popToViewController(vc, animated: true)
// found it, so break out of the for loop
break
}
}
if !bFoundLogin {
// we didn't find LoginViewController in stack, so
// replace current VC with LoginVC
//if let loginVC = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "LOGIN") as? LoginViewController {
if let loginVC = UIStoryboard(name: "AnimConstraints", bundle: nil).instantiateViewController(withIdentifier: "LOGIN") as? LoginViewController {
// insert loginVC before last item
viewControllersArray.insert(loginVC, at: viewControllersArray.count - 1)
// set the NavVC's array of controllers
navVC.setViewControllers(viewControllersArray, animated: false)
// pop back one level (to our inserted loginVC)
navVC.popViewController(animated: true)
}
}
}
}
使用循环来“查找”堆栈中的LoginViewController
,即使它不是“下一个在线”,也可以“弹出”它,也不需要你的dm.isLoginViewLoaded
跟踪(除非您在其他地方使用它)。