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 に答える