按类或其他标记

时间:2015-11-09 06:43:31

标签: ios objective-c uiviewcontroller storyboard

通常会看到示例代码从root访问视图层次结构以获取指向特定视图控制器的指针,如下所示:

UITabBarController *tabBC = (UITabBarController *)self.window.rootViewController;
UINavigationController *navC = [tabBarController viewControllers][0];
MyCustomTableViewController *myVC = [navigationController viewControllers][0];

这是绝望的脆弱,每次修改故事板订单时都会破坏。似乎需要的是一个UIViewController方法,如:

/*! recurse through child VCs to find instances of class */
-(NSArray*) childVCsOfClass:(Class)targetClass;

或可能:

 -(NSArray*) childVCsPassingTest: // some useful block

我写了这篇废话来完成找到第一个实例的简单案例,但仍然怀疑我忽略了一些明显的事情:

/*! Search through hierarchy for correct view controller
    TODO: Should be a class extension of ViewController, assuming Apple didn't write it yet
    TODO: The double loops are suspect...
*/
UIViewController* FirstChildViewControllerMatchingClass(UIViewController* rootVC, Class targetClass) {
    UIViewController *thisController = rootVC;
    UIViewController* foundInstance = nil;

    if([thisController isKindOfClass:targetClass]) {
        return thisController;  // found it.
    }
    // Special case all the collections, etc.
    if([thisController respondsToSelector: @selector(viewControllers)]) {
        for(id vc in [(id)thisController viewControllers] ) {
            foundInstance = FirstChildViewControllerMatchingClass(vc,targetClass);
            if(foundInstance) {
                return foundInstance;   // found it in the tabs
            }
        }
    }
    // chug through other possible children
    if(thisController.childViewControllers) {
        for(UIViewController* kids in thisController.childViewControllers ) {
            foundInstance = FirstChildViewControllerMatchingClass(kids,targetClass);
            if(foundInstance) {
                return foundInstance;
            }
        }
    }
    // have I missed other possible children...?
    return nil;
}

我并不是特别要求对此代码进行评论,我甚至没有测试过,我正在试图弄清楚Apple(或其他人)是否已经编写了一个坚固且完整的版本而且我还没有搜索了正确的文件。 (OTOH建设性的批评是受欢迎的;)

0 个答案:

没有答案