Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to iterate all the UIViewControllers on the app

I have a xib with this structure:

- Tab Bar Controller
-- Tab Bar
-- NavigationController
--- Navigation Bar
--- News List View Controller
---- Navigation Item
--- Tab Bar Item

-- NavigationController
--- Navigation Bar
--- News List View Controller
---- Navigation Item
--- Tab Bar Item
-- NavigationController
--- Navigation Bar
--- News List View Controller
---- Navigation Item
--- Tab Bar Item
[...]

How can I code a loop to take each UIViewController (News List View Controller) in each iteration?

like image 958
Jimmy Avatar asked Oct 18 '11 20:10

Jimmy


2 Answers

Access them codewise like this:

NSArray * controllerArray = [[self navigationController] viewControllers];

for (UIViewController *controller in controllerArray){
   //Code here.. e.g. print their titles to see the array setup;
   NSLog(@"%@",controller.title);
}
like image 135
Wolfert Avatar answered Nov 17 '22 02:11

Wolfert


If you're using iOS 5 you can do something like this:

- (void) processViewController: (UIViewController *) viewController {
    //do something with viewcontroller here
    NSLog(@"I'm viewcontroller %@", viewController);
    for ( UIViewController *childVC in viewController.childViewControllers ) {
        [self processViewController:childVC];
    }
}

and start the whole fun with:

[self processViewController:myRootViewController]; //would be the tabbarcontroller in your case

Edit: I'm not sure what you want to achieve here, but this code is for going through the whole tree.

Edit 2:

For iOS 4 try something like this:

- (void) processViewController: (UIViewController *) viewController {
    //do something with viewcontroller here
    NSLog(@"I'm viewcontroller %@", viewController);

    if ( [viewController isKindOfClass:[UITabBarController class]] ) {
        for ( UIViewController *childVC in ((UITabBarController *)viewController).viewControllers ) {
            [self processViewController:childVC];
        }
    }
    else if ( [viewController isKindOfClass:[UINavigationController class]] ) {
        for ( UIViewController *childVC in ((UINavigationController *)viewController).viewControllers ) {
            [self processViewController:childVC];
        }
    }
}

Note: You'd need to add any custom viewcontroller which have subviewcontrollers. If you have any.. The Root viewcontroller gets it started again.

like image 5
huesforalice Avatar answered Nov 17 '22 01:11

huesforalice