如何返回导航堆栈?

我的应用程序有7个后续视图控制器:VC1 – VC7
在我的导航栏中,我有一个后退button,可以执行操作:tapped和longPressed。 当在任何VC中按下backButton时,应用程序应该转到VC2并将其显示为如同用户从VC1到VC2一样,具体来说就是:用右后退button轻击操作。

这是我的代码UILongPressGestureRecognizer:

func longPressAction(gestureRecognizer: UIGestureRecognizer) { if (gestureRecognizer.state == UIGestureRecognizerState.Ended) { println("Long press ended") } else if (gestureRecognizer.state == UIGestureRecognizerState.Began) { println("Long press detected") let mainStoryboard = UIStoryboard(name: "Main", bundle: NSBundle.mainBundle()) let vc: ViewController2 = mainStoryboard.instantiateViewControllerWithIdentifier("vc2") as! ViewController2 navigationController?.pushViewController(vc, animated: true) } } 

我怎样才能回到导航堆栈的正确位置?

您可以在导航控制器中设置视图控制器的数组:

 let viewControllersArray = [VC1,VC2] self.navigationController.setViewControllers(viewControllersArray, animated: true) 

编辑

在你的情景

 else if (gestureRecognizer.state == UIGestureRecognizerState.Began) { println("Long press detected") let mainStoryboard = UIStoryboard(name: "Main", bundle: NSBundle.mainBundle()) let vc1: ViewController1 = mainStoryboard.instantiateViewControllerWithIdentifier("vc1") as! ViewController1 let vc2: ViewController2 = mainStoryboard.instantiateViewControllerWithIdentifier("vc2") as! ViewController2 let VCArray = [vc1,vc2] self.navigationController.setViewControllers(VCArray, animated: true) } 

我可以想到两种方法来实现这一点:

  1. 将VC2设置为您的根视图控制器,然后使用popToRootViewControllerAnimated 。 它的清洁IMO,如果VC2是你的主要控制器经常被调用。

  2. 维持一个布尔值来表示VC2是否被加载到堆栈中。 如果加载,那么只需使用popToViewController ,如果尚未加载到内存中,则只需pushViewController并推送VC2。