How to go back in the navigation stack?

丶灬走出姿态 提交于 2019-12-23 18:06:32

问题


My app has 7 subsequent view controllers: VC1 - VC7
In my navigation bar I have a back button with to actions: tapped and 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.

This is my code for 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 ?


回答1:


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



回答2:


I can think of two ways to accomplish this:

  1. Set VC2 as your Root view Controller and then use popToRootViewControllerAnimated. Its cleaner IMO if VC2 is your primary Controller that gets called so often.

  2. Maintain a boolean to denote if VC2 is loaded in the stack yet. If loaded then just use popToViewController, and if not yet loaded in memory then just pushViewController and push VC2.



来源:https://stackoverflow.com/questions/32518980/how-to-go-back-in-the-navigation-stack

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!