从导航阵列中删除以前的控制器

时间:2019-04-03 18:42:20

标签: swift xcode uinavigationcontroller

你好,在我的应用中,我从第5或第6控制器点随机移动到所有控制器,但我又移至第一个控制器,但是当我返回第5或第6控制器时,我希望当我再次移至第一个控制器时想删除所有以前的控制器,当我返回时什么也没发生

例如,当我移至第5位第6位然后第1位 A-> B-> C-> D-> A

但是我想要这个 A> B> C> D> A(在A点上删除所有以前的记录)

我这样移动

let vc = UIStoryboard.init(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "HomeViewController") as! HomeViewController
        NavigationController.pushViewController(vc, animated: animated)

1 个答案:

答案 0 :(得分:0)

您可以使用navigationController?.setViewControllers([vc], animated: true)

示例:

class ViewController1: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        print("navigationController?.viewControllers.count = \(navigationController?.viewControllers.count ?? -1)")
    }

    deinit {
        print("ViewController1 deinit")
    }

    @IBAction func pushButtonTapped(_ sender: Any) {
        let vcIdentifier = "SecondVC"
        let storyboard = UIStoryboard(name: "Main", bundle: nil)
        let vc = storyboard.instantiateViewController(withIdentifier: vcIdentifier)
        navigationController?.pushViewController(vc, animated: true)
    }

}

class ViewController2: UIViewController {

    deinit {
        print("ViewController2 deinit")
    }

    @IBAction func push2ButtonTapped(_ sender: Any) {
        let vcIdentifier = "ThirdVC"
        let storyboard = UIStoryboard(name: "Main", bundle: nil)
        let vc = storyboard.instantiateViewController(withIdentifier: vcIdentifier)
        navigationController?.pushViewController(vc, animated: true)
    }
}

class ViewController3: UIViewController {

    deinit {
        print("ViewController3 deinit")
    }

    @IBAction func push3ButtonTapped(_ sender: Any) {
        let vcIdentifier = "FirstVC"
        let storyboard = UIStoryboard(name: "Main", bundle: nil)
        let vc = storyboard.instantiateViewController(withIdentifier: vcIdentifier)
        //this is what you want
        navigationController?.setViewControllers([vc], animated: true)
    }
}

打印输出:

navigationController?.viewControllers.count = 1
navigationController?.viewControllers.count = 1
ViewController1 deinit
ViewController2 deinit
ViewController3 deinit