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 ?
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:
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.
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.