简体   繁体   中英

Add viewcontroller to navigation controller programmatically then push another view controller

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.

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)
}

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM