navigationController popToViewController无法在swift 3中运行

时间:2016-11-19 13:10:39

标签: ios uinavigationcontroller swift3

我希望在swift 3.0中使用popToViewController navigationController
为此我写了下面的代码,但没有按预期工作。

let controllers = self.navigationController?.viewControllers
for vc in controllers! {
    if vc is HomeViewController {
        self.navigationController?.popToViewController(vc, animated: true)
    }
}

我还写了下面的代码,但这也有效。

for vc in controllers! {
    if vc.isKind(of:HomeViewController.self) {
        self.navigationController?.popToViewController(vc, animated: true)
    }
}

请帮我解决这个问题。

3 个答案:

答案 0 :(得分:4)

试试这是popToViewController

的代码

Swift 3.0

  let controllers = self.navigationController?.viewControllers
      for vc in controllers! {
        if vc is HomeViewController {
          _ = self.navigationController?.popToViewController(vc as! HomeViewController, animated: true)
        }
     }

答案 1 :(得分:3)

Swift 3.1

如果你是UINavigationController的扩展名,请确保使用self.popToViewController而非self.navigationController.popToViewController

extension UINavigationController {
    func popToViewController<T: UIViewController>(withType type: T.Type) {
         for viewController in self.viewControllers {
             if viewController is T {
               self.popToViewController(viewController, animated: true)
              return
         }
      }
   }
}

答案 2 :(得分:0)

尝试一下,这是popToViewController的代码

更新Swift 4.2

let controllers = self.navigationController?.viewControllers
         for vc in controllers! {
           if vc is ListViewController {
             _ = self.navigationController?.popToViewController(vc as! ListViewController, animated: true)
           }
        }