如何迭代应用程序上的所有UIViewControllers

时间:2011-10-18 20:56:13

标签: iphone objective-c ios

我有一个这种结构的xib:

- 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
[...]

如何编写循环以在每次迭代中获取每个UIViewController(新闻列表视图控制器)?

2 个答案:

答案 0 :(得分:10)

按照代码方式访问它们:

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

答案 1 :(得分:5)

如果你使用的是iOS 5,你可以这样做:

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

并以:

开始整个乐趣
[self processViewController:myRootViewController]; //would be the tabbarcontroller in your case

编辑:我不确定你想在这里实现什么,但这段代码是为了遍历整个树。

编辑2:

对于iOS 4,请尝试以下方法:

- (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];
        }
    }
}

注意:您需要添加任何具有subviewcontrollers的自定义viewcontroller。如果你有..根视图控制器再次启动它。