1

I want to append couple of viewcontrollers in array of viewcontroller of a navigation controller, then want push third viewcontroller of the same navigation controller. My code is as follows

let navigationController = getCurrentNavController()

let listVC = UIStoryboard.loadListViewController()
navigationController.viewControllers.append(listVC)
                
let detailVC = UIStoryboard.loadDetailsViewController()
navigationController.viewControllers.append(detailVC)
                
let thirdVC = UIStoryboard.loadThird()
navigationController.pushViewController(thirdVC, animated: true)

The thirdVC is push on the navigation controller, the problem is when i pop thirdVC, I don't find detailVC or listVC. Is this possible? if yes please help.

2 Answers 2

3

Don't edit the viewControllers array directly. That is why the animated parameter exists.

A solution may be to add the viewControllers in between after 0.25 seconds (the duration of the push animation) by doing:

let navigationController = getCurrentNavController()
var viewControllers = navigationController.viewControllers

let listVC = UIStoryboard.loadListViewController()
viewControllers.append(listVC)
                
let detailVC = UIStoryboard.loadDetailsViewController()
viewControllers.append(detailVC)
                
let thirdVC = UIStoryboard.loadThird()
viewControllers.append(thirdVC)
navigationController.pushViewController(thirdVC, animated: true)

DispatchQueue.main.asyncAfter(now() + 0.25) {
    navigationController.setViewControllers(viewControllers, animated: false)
}
Sign up to request clarification or add additional context in comments.

1 Comment

Worked ;-) Thanks, One doubt is why do i need to push thirdVC If i am appending it in viewControllers array
1

As mentioned, you do not want to modify the navigation controller's viewControllers directly.

But, you also don't need to do any explicit "pushing":

    let navigationController = getCurrentNavController()

    let listVC = UIStoryboard.loadListViewController()
    let detailVC = UIStoryboard.loadDetailsViewController()
    let thirdVC = UIStoryboard.loadThird()

    var vcs = navigationController.viewControllers

    vcs.append(listVC)
    vcs.append(detailVC)
    vcs.append(thirdVC)

    navigationController.setViewControllers(viewControllers, animated: true)

This will animate thirdVC in from the current view controller, just as if you had pushed it, but it will also insert listVC and detailVC into the navigation controller's stack so the "Back" button will take you through detailVC and listVC.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.