清除/删除 NavigationController 中的多个 ViewController

Clear/Remove multiple ViewController in NavigationController

提问人:esantiago 提问时间:9/15/2023 更新时间:9/15/2023 访问量:30

问:

我希望你能帮我解决这个问题。

我正在开发具有多个 ViewController 的 iOS 应用程序,如下图所示。enter image description here

我从 VC1 导航到 VC2,从 VC2 导航到 VC3,直到到达 VCn。当我到达这个 ViewController 时,我需要转到 VC4。我知道我可以对 VC4 进行 segue,但问题是它将存储在导航堆栈中,这是我想避免的。

如何从 VCn 导航到 VC4,同时清除导航堆栈(VC2、VC3...VCn),然后从 VC4 返回到 VC1?

我希望你能帮助我!😄

iOS Swift Xcode UIVieviceController 情节提要

评论

0赞 Sweeper 9/15/2023
是要转到新的 VC4,还是要返回到现有的 VC4?
0赞 esantiago 9/15/2023
@Sweeper我想转到尚未在导航中显示的 VC4,它不在导航堆栈中

答:

0赞 Sweeper 9/15/2023 #1

您需要做的就是将导航控制器的属性设置为包含两个元素的数组 - 根视图控制器 (VC1) 和新的 VC4。viewControllers

if let navigationController {
    let vc4 = ... // initialise VC4 appropriately
    // make the array
    let newStack = [navigationController.viewControllers[0], vc4]
    // this sets viewControllers, with a "push" transition
    navigationController.setViewControllers(newStack, animated: true)
}

如果您想要一个“pop”过渡,请首先删除除第一个和最后一个之外的所有元素,然后在剩余的 2 个 VC 之间插入 VC4。然后你可以去VC4。viewControllerspopViewController(animated: true)

if let navigationController {
    let vc4 = ... 
    navigationController.viewControllers.removeSubrange(1..<navigationController.viewControllers.count - 1)
    navigationController.viewControllers.insert(vc4, at: 1)
    navigationController.popViewController(animated: true)
}