How to pop view controller to one of the previous view controllers in swift?

后端 未结 4 1396
长情又很酷
长情又很酷 2020-12-15 05:46

I have been trying to pop my view controller to one of previous view controllers in my view stack. Assume that, There are firstVC, secondVC, thirdVC and fourthVC

相关标签:
4条回答
  • 2020-12-15 05:59

    After lots of effort I have created swift extension of back to a particular view controller in Swift 3.0.

    extension UINavigationController {
    
        func backToViewController(viewController: Swift.AnyClass) {
    
                for element in viewControllers as Array {
                    if element.isKind(of: viewController) {
                        self.popToViewController(element, animated: true)
                    break
                }
            }
        }
    }
    

    Method calling:

       self.navigationController?.backToViewController(viewController: BarCodeScannerVC.self)
    
    0 讨论(0)
  • 2020-12-15 06:10

    Here you can do this by the find the controller from the UINavigationController stack and with the help of for loop and check the condition of your desire controller and if the condition gets fulfilled it will pop to the destionation controller.

    let viewControllersStack: [UIViewController] = self.navigationController!.viewControllers
          for firstViewcontroller in viewControllersStack
          {
               if firstViewcontroller is desireViewController
               {
                    self.navigationController!.popToViewController(firstViewcontroller, animated: true)
               }
          }
    
    0 讨论(0)
  • 2020-12-15 06:21

    Instead of doing a generic popViewControllerAnimated: call, use popToViewController:animated:. You could detect if the user has deleted all of the rows in which case, do something like this (otherwise just pop one view controller):

    let viewControllers: [UIViewController] = self.navigationController!.viewControllers as [UIViewController];
    self.navigationController!.popToViewController(viewControllers[viewControllers.count - 2], animated: true);
    
    0 讨论(0)
  • 2020-12-15 06:23

    If you want to pop to a specific view control and dont know the count to go back you can use this:

     let viewControllers: [UIViewController] = self.navigationController!.viewControllers as! [UIViewController];
    
            for aViewController in viewControllers {
                if(aViewController is ViewControllerYouWantToGoTo){
                     self.navigationController!.popToViewController(aViewController, animated: true);
                }
            }
    
    0 讨论(0)
提交回复
热议问题