2
-(UINavigationController *) navigationControllerOfParentOrSelf //These 2 functions are short so I just go ahead
{
    UIViewController * current=self;
    while (current) {
        UINavigationController * nav = current.navigationController;
        if (nav) {
            return nav;
        }
        current=current.parentViewController;
    }
    return nil;
}

-(UITabBarController *) tabBarControllerOfParentOrSelf
{
    UIViewController * current=self;
    while (current) {
        UITabBarController * tc = current.tabBarController;
        if (tc) {
            return tc;
        }
        current=current.parentViewController;
    }
    return nil;
}

看起来那里有很多重复的代码。

基本上我只想知道 UIViewController 是否在 UINavigationController 内。当 UIViewController 是 childViewController 时,navigationController 属性通常为 nil

4

2 回答 2

2

我会建议这样的事情:

-(UINavigationController *) navigationControllerOfParentOrSelf
{
    return [self parrentControllerOfParrentOrSelfWithGetter: @selector(navigationController)];
}

-(UITabBarController *) tabBarControllerOfParentOrSelf
{
    return [self parrentControllerOfParrentOrSelfWithGetter: @selector(tabBarController)];

}

- (id) parrentControllerOfParrentOrSelfWithGetter: (SEL) getter
{
    UIViewController * current=self;
    while (current) {
        id res = [current performSelector: getter];
        if (res) {
            return tc;
        }
        current=current.parentViewController;
    }
    return nil;
}
于 2013-10-15T11:45:46.960 回答
1

你可以这样做:

-(id) getViewController:(BOOL)isNavController
{
     id controller = nil;
     if(isNavController)
     {
        controller  = self.navigationController;
     }
     else
     {
         controller  = self.tabBarController;
     }

     return controller;
}
于 2013-10-15T09:17:36.477 回答