iOS Swift popToViewController by Name

2019-07-11 02:10发布

I'm trying to pop to a viewcontroller which I believe is at index 0. My ViewController name is HomeVC.

 self.navigationController!.popToViewController(self.navigationController!.viewControllers[0] as! UIViewController, animated: true)

However, the code above only pops me back to the most recent viewcontroller. Not sure why it's not going to my HomeVC viewcontroller. Is their a way I can use the ViewController Name to pop to it?

4条回答
We Are One
2楼-- · 2019-07-11 02:20

Add following UINavigationController extension

extension UINavigationController {

    func popToClass<T: UIViewController>(type: T.Type) -> Bool {
        for viewController in self.viewControllers {
            guard let _ = viewController as? T else { continue }
            self.popToViewController(viewController, animated: true)
            return true
        }
        return false
    }

}

Use as follows

let success = navigationController.popToClass(MyVC.self)
查看更多
The star\"
3楼-- · 2019-07-11 02:24

Try this:

for (var i = 0; i < self.navigationController?.viewControllers.count; i++) {
    if(self.navigationController?.viewControllers[i].isKindOfClass(YourDesiredViewController) == true) {
           self.navigationController?.popToViewController(self.navigationController!.viewControllers[i] as! DestinationViewController, animated: true)   
           break;
    }
}
查看更多
霸刀☆藐视天下
4楼-- · 2019-07-11 02:26

You can use popToRootViewControllerAnimated to pop to the View controller at index zero.

It returns an array of view controllers that were popped, that might help you in debugging the issue.

查看更多
祖国的老花朵
5楼-- · 2019-07-11 02:28
    for viewController in (self.navigationController?.viewControllers)! {
        if(viewController is YourViewController) {
            self.navigationController?.popToViewController(viewController, animated: true)
            break;
        }
    }

I solved it like this.

查看更多
登录 后发表回答