Search code examples
iosswiftseguedismissunwind-segue

Segueing to New View Controller while Dismissing previous without navigation controller: swift


Hello I am pretty annoyed with this:

Originally, I had many segues in my storyboard. Each button at bottom of tool bar would segue to various view controllers. As you can imagine, that is a lot of segues for 6 different items on toolbar. After segueing, each action would call self.dismiss and everything would be ok.

Recently, I wanted to clean up the storyboard.

I created the function:

 extension UIViewController {

    func segue(StoryboardID: String) {
    let popOverVC = UIStoryboard(name: "Main", bundle: 
    nil).instantiateViewController(identifier: StoryboardID)
    popOverVC.modalPresentationStyle = UIModalPresentationStyle.fullScreen
    popOverVC.modalTransitionStyle = .crossDissolve
    self.dismiss(animated: false, completion: nil)
    print("dismissed")
    self.present(popOverVC, animated: false, completion: nil)
    print("presented")
  }

}

What I am seeing is that the dismiss dismisses the new view controller from appearing. It essentially goes back to my first view controller presented upon launch. I want to dismiss all view controllers so that I don't keep piling up my views.

Thanks


Solution

  • The problem is that you present your popOverVC from a view controller that is being dismissed, so your popOverVC will never be shown as its parent is being dismissed.

    Not sure how your architecture is exactly but you would either need to use the delegate pattern to tell the parent when to segue, for example:

    self.dismiss(animated: true) {
        self.delegate?.didDismiss(viewController: self)
    }
    

    Or to use some trick to get the top most view controller to present your popOverVC after the current view has been dismissed, ex:

    self.dismiss(animated: true) {
        var topController: UIViewController = UIApplication.shared.windows.filter{$0.isKeyWindow}.first!.rootViewController!
        while (topController.presentedViewController != nil) {
            topController = topController.presentedViewController!
        }
        topController.present(popOverVC, animated: true)
    }
    

    But I agree with @Paulw11, a UITabBarController seem like a much better option for what you're trying to do.