我有以下方式的6个viewControllers。
VCA
,VCB
,VCC
,VCD
,VCE
,VCF
。
mainVC
- > VCA
- > VCB
- > VCC
- > VCD
... {{1 }}
VCE
- > mainVC
- > VCA
... VCD
( - >)通过segues连接,而(...)VCF
和VCE
是以编程方式VCF
。
我的问题是如何在pushed in navigationController
上的VCD
UIBarButton上从VCE
,VCF
或VCA
到Back
弹出多个viewControllers < / p>
根据此StackOverFlow问题Link和Link: -
尝试了这段代码,但它没有用。
navigationController
答案 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)