Search for a storyboard or view hierarchy for a specific child view controller by class or other tag

Usually, to see example code that looks at the hierarchy of views from root to get a pointer to a specific view controller, for example:

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

It is hopelessly fragile, breaking every time a storyboard adjustment is revised. What seems necessary is the UIViewController method, for example:

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

or perhaps:

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

I wrote this departure in order to perform a simpler case of finding the first instance, but still suspect that I'm missing something obvious:

/*! 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 ;)

+4

Source: https://habr.com/ru/post/1615002/


All Articles