Search code examples
iosuiviewcontrolleruinavigationcontroller

How to programmatically pop a view controller and present a new one


What I am trying to do is present a viewController and when the user touches a button I want to call popViewController and then present a different viewController. But I cannot figure out how to do it.

Some of the things I have tried are call pop and then immediately call present, call present after a delay, pup the pop with a completion block and then in the completion block call present, as well as other ideas.

I think I am over complicating the whole thing, i believe their should be an easy way to do this.

Thanks for any help with this.

CLARIFICATION:

I do this on a touch:

        if let vc = UIStoryboard(name: "Listing", bundle: nil).instantiateInitialViewController() as? ListingViewController
    {
        vc.listing = listing
        vc.editListing = forEdit
        vc.title = " "
        self.navigationController?.pushViewController(vc, animated: true)
    }

From that VC when the user touches a button I do this:

self.navigationController?.popViewController(animated: true)

When the VC goes away I want to do something like this:

        if let vc = UIStoryboard(name: "CreateListing", bundle: nil).instantiateInitialViewController() as? NewCreateListingViewController
    {
        vc.bMakeSimiliar = makeSimiliar
        vc.listing = listing
        vc.editListing = editListing
        vc.title = " "
        self.navigationController?.pushViewController(vc, animated: true)
    }

Basically my user is viewing the first controller which is a listing, from the listing VC he touches a button to add a new listing, so I want to dismiss the listing view controller and present him with the create listing view controller.

When I execute the above code to present the new VC nothing happens. I am doing this immediately after the popViewController.


Solution

  • You don't use pop to present next controller in stack. Pop actually navigates back from the current controller.

    To perform what you're trying to achieve you need to call navigationController.pushViewController(viewController: UIViewController, animated: Bool) method.

    In order to get back to some previous view controller you use: navigationController.popViewController(animated: Bool)

    In order to get to the root view controller you use: navigationController.popToRootViewController(animated: Bool)

    In order to get to some specific view controller in the stack you use: popToViewController(viewController: UIViewController, animated: Bool)