Mrugesh Tank
Mrugesh Tank

Reputation: 3560

navigationController popToViewController not working in swift 3

I want use popToViewController of navigationController in swift 3.0.
For that I written below code but nothing working as expected.

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

I also wrote below code, but that is also working.

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

Please help me to solve this problem.

Upvotes: 2

Views: 3917

Answers (3)

Puji Wahono
Puji Wahono

Reputation: 348

Try this is your code for popToViewController

Update Swift 4.2

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

Upvotes: 0

Cason Le
Cason Le

Reputation: 53

Swift 3.1

if you are extension the UINavigationController, make sure you use self.popToViewController not 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
         }
      }
   }
}

Upvotes: 4

Anand Nimje
Anand Nimje

Reputation: 6251

Try this is your code for 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)
        }
     }

Upvotes: 5

Related Questions