Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Better way to select view controller using popToViewController: animated:

Consider:

[self.navigationController popToViewController:[[self.navigationController viewControllers]objectAtIndex:1] animated:YES];

Is there a better way to get index of the view controller to pop to? This way if I do something to the nav stack, I don't have to go back and edit this. I was thinking of maybe storing it in a ivar on the VC or using #define macros. Any ideas?

Edit: The stack has four view controllers. I used this code to pop from the fourth to the second.

like image 635
Myron Slaw Avatar asked Jan 19 '23 16:01

Myron Slaw


2 Answers

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

[self popToViewController:yourViewController animated:YES];

Of course, this assumes the stack will have only one instance of the controller class that you are looking for. If there are more, I think you can choose to store it in a globally accessible location like the application delegate.


Note - typically if you are using this in a UIViewController, that final line of code would be:

[self.navigationController popToViewController:seuleMainPage animated:YES];
like image 199
Deepak Danduprolu Avatar answered Jan 30 '23 20:01

Deepak Danduprolu


You can replace code in the question with a simple category on UINavigationController which can be used wherever it's appropriate.

@interface UINavigationController(indexPoping)
- (void)popToViewControllerAtIndex:(NSInteger)newVCsIndex animated:(BOOL)animated;
@end

@implementation UINavigationController(indexPoping)
- (void)popToViewControllerAtIndex:(NSInteger)newVCsIndex animated:(BOOL)useAnimation
{
    if (newVCsIndex < [self.viewControllers count]) {
        [self popToViewController:[self.viewControllers objectAtIndex:newVCsIndex] animated:useAnimation];
    }
}


// Usage

...

NSInteger indexToPopTo = ...
[self.navigationController popToViewControllerAtIndex:indexToPopTo animated:YES]

...
like image 22
Zapko Avatar answered Jan 30 '23 20:01

Zapko