如何以编程方式解开或在背面UIBarButton上弹出多个viewControllers?

时间:2018-01-16 12:58:18

标签: ios swift uiviewcontroller uibarbuttonitem

我有以下方式的6个viewControllers。 VCAVCBVCCVCDVCEVCF

mainVC - > VCA - > VCB - > VCC - > VCD ... {{1 }}

VCE - > mainVC - > VCA ... VCD

( - >)通过segues连接,而(...)VCFVCE是以编程方式VCF

我的问题是如何在pushed in navigationController上的VCD UIBarButton上从VCEVCFVCABack弹出多个viewControllers < / p>

enter image description here

根据此StackOverFlow问题LinkLink: -

尝试了这段代码,但它没有用。

navigationController

2 个答案:

答案 0 :(得分:0)

如果您知道VCA已被推送到mainVC,那么您的导航控制器堆栈为[mainVC, VCA, VCB, ..., VCF][mainVC, VCA, VCD, ..., VCF],因此您希望在项目中弹回VC堆栈中的一个:

func back(sender: UIBarButtonItem) {

        if let vc = navigationController?.viewControllers[1] {
            _ = navigationController?.popToViewController(vc, animated: true)
        }

}

如果你真正想做的是回到导航控制器的 root VC,你可以简单地说:

func back(sender: UIBarButtonItem) {

        _ = navigationController?.popToRootViewController(animated: true)

}

修改

其他信息:

// if you want to pop to the First VC, regardless of VC type
func popToFirst() {

    if let vc = navigationController?.viewControllers[1] {
        _ = navigationController?.popToViewController(vc, animated: true)
    } else {
        print("NO VC found as element 1 in navigation controller's stack")
    }

}

// if you want to pop to the First VC, but
// *only* if it is an instance of VCAViewController
func popToFirstOnlyIfA() {

    if let vc = navigationController?.viewControllers[1] as? VCAViewController {
        _ = navigationController?.popToViewController(vc, animated: true)
    } else {
        print("viewControllers[1] is NOT an instance of VCAViewController")
    }

}

// if you want to pop to an instance of VCAViewController,
// whether it's the root, first, second, third, etc VC in the stack
func popToAAnywhereInTheStack() {

    guard let aVCs = navigationController?.viewControllers else {
        print("No Array of View Controllers from navigationController!")
        return
    }

    for vc in aVCs {
        if vc is VCAViewController {
            _ = navigationController?.popToViewController(vc, animated: true)
            return
        }
    }

    print("No instance of VCAViewController found in the stack")

}

// if you simply want to pop to the navigation controller's Root VC
func popToRoot() {

    _ = navigationController?.popToRootViewController(animated: true)

}

答案 1 :(得分:-1)

从当前视图控制器(它将是最后一个)和视图控制器之间的navigationController?.viewControllers删除所有视图控制器,然后执行navigationController?.popViewController(animated: true)