简体   繁体   English

如何回到导航堆栈?

[英]How to go back in the navigation stack?

My app has 7 subsequent view controllers: VC1 - VC7 我的应用程序有7个后续视图控制器:VC1 - VC7
In my navigation bar I have a back button with to actions: tapped and longPressed. 在我的导航栏中,我有一个带有动作的后退按钮:tapped和longPressed。 When the backButton gets pressed long in any VC, the app should go to VC2 and present it as if the user went from VC1 to VC2, specifically: with the right back button tapped action. 当backButton在任何VC中被长按时,应用程序应该转到VC2并呈现它,好像用户从VC1转到VC2,具体是:使用右后退按钮轻击动作。

This is my code for UILongPressGestureRecognizer: 这是我的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)

    }

}

How can I go back to the right place in the navigation stack ? 如何返回导航堆栈中的正确位置?

You can set your array of View Controllers in the Navigation Controller: 您可以在导航控制器中设置视图控制器阵列:

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

EDIT 编辑

In Your Scenario 在您的场景中

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

I can think of two ways to accomplish this: 我可以想到两种方法来实现这个目标:

  1. Set VC2 as your Root view Controller and then use popToRootViewControllerAnimated . 将VC2设置为Root视图Controller,然后使用popToRootViewControllerAnimated Its cleaner IMO if VC2 is your primary Controller that gets called so often. 如果VC2是你经常被调用的主要控制器,它的清洁IMO。

  2. Maintain a boolean to denote if VC2 is loaded in the stack yet. 保持一个布尔值来表示VC2是否已加载到堆栈中。 If loaded then just use popToViewController , and if not yet loaded in memory then just pushViewController and push VC2. 如果加载然后只使用popToViewController ,如果还没有加载到内存中那么只需pushViewController并推送VC2。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM