2

am using storyboard with navigation controller having three viewControllers, the root controller and the other two remaining labeled as 1 2 and 3 respectively. as shown in the image enter image description here

Now the problem is that i want to come back to the rootViewController and 2nd viewController from the 3rd one using single unWind Segue. I means if i pushed 3rd controller from root than unwind let me back to root controller and if i pushed from 2nd than it let me back to 2nd viewController. I wan to use only single button for going back. any help will be appreciated . Thanks

Nisar Ahmad
  • 885
  • 1
  • 10
  • 25

1 Answers1

1

You need to specify an IBAction and attach that action to the button you want to press to move backwards to any of the previous View Controllers. Inside this action method, you can specify to which controller you want to unwind to.

Now, according to the image, you want to unwind to the 2nd Controller from the 3rd controller. So, in your 3rd controller, attach the following action method to the button. Also, go to the storyboard and give each of your view controller's a storyboard identifier. Let's assume, your Second View Controller's storyboard identifier is "secondViewController".

-(IBAction)unwindToThisViewController:(UIStoryboardSegue *)unwindSegue
    {

    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
    SecondViewController *secondVC = [storyboard instantiateViewControllerWithIdentifier:@"secondViewController"];
    int index = [self getMyDesiredViewControllerIndex:secondVC];
    [self.navigationController popToViewController:[[self.navigationController viewControllers]objectAtIndex:index] animated:YES];
    }

Your getMyDesiredViewControllerIndex method should look like-

-(int)getMyDesiredViewControllerIndex:(UIViewController*)desiredVC{

    int i=0;
    for(UIViewController *vc in [self.navigationController viewControllers]){
        if([vc isKindOfClass:[desiredVC class]]){
            return i;
        }
        i++;
    }
    return 0;
}

This way, you can jump to any View Controller you want. Just specify your desired View Controller and get its index from the getMyDesiredViewControllerIndex and pop to that controller.

Hope this helps!

Natasha
  • 6,651
  • 3
  • 36
  • 58