如何迭代应用程序中的所有UIViewControllers
我有一个这个结构的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(新闻列表视图控制器)在每个迭代?
像这样访问他们代码:
NSArray * controllerArray = [[self navigationController] viewControllers]; for (UIViewController *controller in controllerArray){ //Code here.. eg print their titles to see the array setup; NSLog(@"%@",controller.title); }
如果你使用的是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]; } } }
注意:您需要添加任何具有子视图控制器的自定义视图控制器。 如果你有任何..根视图控制器再次启动它。