清除/删除NavigationController中的多个ViewController

问题描述 投票:0回答:1

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

我正在使用多个 ViewController 开发这个 iOS 应用程序,如下图所示。

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

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

希望你能帮助我! 😄

ios swift xcode uiviewcontroller storyboard
1个回答
0
投票

您需要做的就是将导航控制器的

viewControllers
属性设置为两个元素的数组 - 根视图控制器 (VC1) 和新的 VC4。

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

如果您想要“弹出”过渡,请首先删除

viewControllers
中除第一个和最后一个之外的所有元素,然后在剩余 2 个 VC 之间插入 VC4。然后就可以
popViewController(animated: true)
进入VC4了。

if let navigationController {
    let vc4 = ... 
    navigationController.viewControllers.removeSubrange(1..<navigationController.viewControllers.count - 1)
    navigationController.viewControllers.insert(vc4, at: 1)
    navigationController.popViewController(animated: true)
}
© www.soinside.com 2019 - 2024. All rights reserved.