Sunday, June 9, 2013

UINavigationController popToViewController example in Objective C (iOS).


UINavigationController popToViewController

Pops view controllers until the specified view controller is at the top of the navigation stack.

- (NSArray *)popToViewController:(UIViewController *)viewController animated:(BOOL)animated

Parameters of [UINavigationController popToViewController]
viewController
The view controller that you want to be at the top of the stack.
animated
Set this value to YES to animate the transition. Pass NO if you are setting up a navigation controller before its view is displayed.

Return Value
An array containing the view controllers that were popped from the stack.

Discussion of [UINavigationController popToViewController]
For information on how the navigation bar is updated, see “Updating the Navigation Bar.”

UINavigationController popToViewController example.
- (void) popControllersNumber:(int)number
{
    if (number <= 1)
        [[self navigationController] popViewControllerAnimated:YES];
    else
    {
        NSArray* controller = [[self navigationController] viewControllers];
        int requiredIndex = [controller count] - number - 1;
        if (requiredIndex < 0) requiredIndex = 0;
        UIViewController* requireController = [[[self navigationController] viewControllers] objectAtIndex:requiredIndex];
        [[self navigationController] popToViewController:requireController animated:YES];
    }
}

Example of [UINavigationController popToViewController].
TasksViewController *taskViewController = [[TasksViewController alloc] initWithNibName:nil bundle:nil];

if ([navigationController.viewControllers indexOfObject:taskViewController] == NSNotFound)
{
    [navigationController pushViewController:taskViewController animated:animated];
}
else
{
    [navigationController popToViewController:taskViewController animated:animated];
}

UINavigationController popToViewController example.
YourViewController *yourViewController;
for ( UIViewController *viewController in self.navigationController.viewControllers ) {
    if ( [viewController isMemberOfClass:[YourViewController class]] ) {
        yourViewController = (YourViewController*)viewController;
        break;
    }
}

[self popToViewController:yourViewController animated:YES];

End of UINavigationController popToViewController example article.