2014-05-15 75 views
1

我正在爲一個項目設計一個自定義UIViewContainerController。我在此容器中保存了一個contentView以管理我的Childviewcontroller's視圖。當我單獨添加childviewcontroller時,它工作正常。但是一些childviewcontrollers必須使用「導航控制器」&進行初始化,這是我遇到實現問題的地方。將帶有NavigationController的ChildViewController添加到ContainerController

我用平時initWithRootViewController方法上「navigationcontroller」給init(初始化)我的「childvc」 &那我怎麼與導航欄一起加入這個我contentView

這是我使用的代碼「childvc」沒有「導航控制器」&它工作正常。

// in my containerview controller's add childview method. 
ChildViewController1 *vc = [ChildViewController1 new]; 

[self addChildViewController:vc]; // self = container vc 
vc.view.frame = self.contentView.bounds; 
[self.contentView addSubview:vc.view]; // contentView is the space i've kept to add childvcs 
[vc didMoveToParentViewController:self]; 

現在,當我嘗試使用「childvc」與「navigationcontroller」初始化(因爲有這個「childvc」甲流),我得到的錯誤&什麼,我需要知道的是我怎麼將它添加到我的contentView以及導航欄。 (就像在tabbarcontroller中)。

這是我使用初始化「childvc」與「導航控制器」的代碼:

ChildViewController1 *vc = [ChildViewController1 new]; 
UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:vc]; 

我做了簡單的工程「Here」公共倉庫。

我已閱讀標籤欄/導航控制器的文檔&在蘋果文檔中創建自定義容器視圖控制器,但似乎缺少重要的東西。 鏈接是「Here」。

回答

1

從看着你的公開回購註釋代碼,你正在嘗試做的是這樣的:

container VC 
    +-- navigation VC 
    |  +-- child VC 
    +-- child VC 

這是不對的,孩子VC只能一次在視圖控制器層次出現。您的層次結構應如下所示:

container VC 
    +-- navigation VC 
     +-- child VC 

下面是如何設置此代碼的代碼的粗略草圖。注意導航控制器(及其視圖)如何完全取代ChildViewController1

// Setup the view controller hierarchy - place this inside 
// your container VC's initializer 
ChildViewController1* vc = [ChildViewController1 new]; 
// With this statement, vc becomes the child of the navigation controller 
UINavigationController* nav = [[UINavigationController alloc] initWithRootViewController:vc]; 
[self.childViewControllers addObject:nav]; 
[nav didMoveToParentViewController:self]; 

// Setup the view hierarchy - place this inside your 
// container VC's loadView override 
nav.view.frame = self.contentView.bounds; 
[self.contentView addSubview:nav.view]; 

正如在評論中提到的,我建議您將視圖控制器層次結構的設置與視圖層次結構的設置分開。

  • 視圖控制器設置的典型場所是初始化期間。您可以看到UINavigationController如何通過其initWithRootViewController:初始值設定項執行此操作。
  • 視圖層次結構設置的規範位置在視圖控制器的覆蓋範圍loadView中。
相關問題