How to iterate all the UIViewControllers on the ap

2020-08-17 18:25发布

问题:

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?

回答1:

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);
}


回答2:

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.