Home > Software engineering >  How to dismiss and pop up a view controller in single click
How to dismiss and pop up a view controller in single click

Time:03-10

I have 3 view controllers In the first view controller (ie. MydownloadViewController) i am using this to push to the another view controller.

  let vc = UIStoryboard.init(name: "Main", bundle: Bundle.main).instantiateViewController(withIdentifier: "ImagePreviewViewController") as? ImagePreviewViewController
self.navigationController?.pushViewController(vc!, animated: true)

and from the image preview controller

 let vc = self.storyboard?.instantiateViewController(withIdentifier: "DeletePopupViewController") as! DeletePopupViewController
 self.present(vc, animated: false, completion: nil)

and from the delete view controller I want to back in my download view controller for this i am doing this -:

 self.dismiss(animated: true, completion:  {
                if let  destinationVC =  presentingVC.navigationController?.viewControllers.filter({$0 is MyDownloadsViewController}).first {
                    presentingVC.navigationController?.popToViewController(destinationVC, animated: false)
                            }

               })

But nothing happens what is wrong with this code.

CodePudding user response:

When your popup dismisses the presenting controller instance would be nil. You may need to hold the reference prior. You may need to do something like the one below.

let presentingController = self.presentingViewController
self.dismiss(animated: true) {
    if let navigationController = presentingController as? UINavigationController,
       let myDownloadsViewController = navigationController.viewControllers.first(
           where: { viewController in
               viewController is MyDownloadsViewController
           }
       ) {
       navigationController.popToViewController(myDownloadsViewController, animated: true)
    }
}

CodePudding user response:

Try this:

let viewControllers: [UIViewController] = self.navigationController?.viewControllers ?? []
                for viewController in viewControllers {
                    if viewController == MyDownloadsViewController() {
                        self.navigationController?.popToViewController(viewController, animated: true)
                    }
                }
  • Related