2013-10-15 90 views
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; 
} 

看起來像很多重複的代碼。如何讓這個UINavigationController尋求更優雅的代碼?

基本上我只想知道一個UIViewController是否在UINavigationController中。事情是navigationController屬性通常爲零時的UIViewController是childViewController

+0

你的循環是沒有意義的。如果'navigationController'屬性不爲零,它將執行一次。如果它是零,它將永遠運行。 –

+0

固定。好的,那不是問題。 –

回答

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; 
} 
+0

好的答案,比我好:) –

1

你可以不喜歡它:

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

    return controller; 
} 
+0

這是一個改進。關鍵是我們使用了一個bool變量。如果我們希望增加更多的財產,那麼呢?我正在思考沿着performSelector(@ navigatorController) –