iOS Swift popToViewController by Name

别等时光非礼了梦想. 提交于 2019-12-24 05:41:14

问题


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?


回答1:


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;
    }
}



回答2:


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.




回答3:


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)



回答4:


    for viewController in (self.navigationController?.viewControllers)! {
        if(viewController is YourViewController) {
            self.navigationController?.popToViewController(viewController, animated: true)
            break;
        }
    }

I solved it like this.



来源:https://stackoverflow.com/questions/31878108/ios-swift-poptoviewcontroller-by-name

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!