Joe
Joe

Reputation: 3961

Popping or dismissing a ViewController

I have a Feedback View Controller that is accessed in 7 locations across 4 different screens.

One way it's presented in a navigationController via pushViewController. The other 6 times it's presented modally.

Here's the function that opens the Feedback VC's

struct Constants{
    static func openFeedback(openFrom: UIViewController, nav:Bool) {
        let fbStoryboard = UIStoryboard(name: "FeedbackViewController", bundle: nil)
        let fbVC = fbStoryboard.instantiateViewController(withIdentifier: "FBSBID")
        fbVC.modalPresentationStyle = .overFullScreen
        fbVC.modalTransitionStyle = .crossDissolve
        if nav {
            openFrom.navigationController?.pushViewController(fbVC, animated: true)
        } else {
            openFrom.present(fbVC, animated: true, completion: nil)
        }
    }
}

The Feedback VC is called with either Constants.openFeedback(openFrom: self, nav: true) or Constants.openFeedback(openFrom: self, nav: false)

Opening the VC works just fine!

Here's my close button on the Feedback View Controller:

@IBAction func closeButtonPressed(_ sender: UIButton) {
    self.dismiss(animated: true, completion: nil)
}

Which works 6 out of the 7 times, when not in the navigation stack. When it's in the navigation stack, the close button does not do anything.

My question is, how do I close out of the Feedback View Controller, based on if it's in the navigationController stack or not?

Upvotes: 0

Views: 56

Answers (1)

Robert Dresler
Robert Dresler

Reputation: 11150

You can simply check if view controller is embedded inside UINavigationController by checking if controller's navigationController is nil or not.

So if it is embedded you can use popViewController(animated:) on navigation controller to "dismiss" pushed controller

if let navCon = navigationController {
    navCon.popViewController(animated: true)
} else {
    dismiss(animated: true)
}

Upvotes: 1

Related Questions