How can I pop specific View Controller in Swift

前端 未结 16 2950
一生所求
一生所求 2020-12-08 02:21

I used the Objective-C code below to pop a specific ViewController.

for (UIViewController *controller in self.navigationController.         


        
16条回答
  •  爱一瞬间的悲伤
    2020-12-08 02:56

    I prefer a generic way to do it.

    I have this extension for the UINavigationController :

    extension UINavigationController {
    
       func backToViewController(vc: Any) {
          // iterate to find the type of vc
          for element in viewControllers as Array {
             if "\(element.dynamicType).Type" == "\(vc.dynamicType)" {
                self.popToViewController(element, animated: true)
                break
             }
          }
       }
    
    }
    

    Let's say I have a FOHomeVC class (who is a UIViewController) instantiated in the navigation stack.

    So I would do this in my code:

    self.navigationController?.backToViewController(FOHomeVC.self)
    

提交回复
热议问题