Sunday, June 9, 2013

UINavigationController popToViewController animated example in Objective C (iOS).


UINavigationController popToViewController animated

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 animated]
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 animated]
For information on how the navigation bar is updated, see “Updating the Navigation Bar.”

UINavigationController popToViewController animated 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 animated].
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 animated 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 animated example article.