蘋果的文檔是這樣說的:
This method creates a parent-child relationship between the current view controller and the object in thechildController parameter. This relationship is necessary when embedding the child view controller’s view into the current view controller’s content. If the new child view controller is already the child of a container view controller, it is removed from that container before being added.
This method is only intended to be called by an implementation of a custom container view controller. If you override this method, you must callsuper in your implementation.
大意就是要求,如果 B VC 的 view 作為 A VC 的 view 的 subView.那么也應該調用 addChildViewController 把B VC 設置為 A VC 的 childViewController.
這樣做有幾個好處:
- 在 A VC 參與 ViewController 跳轉的時候,可以把生命周期回調(viewDidLoad viewWillAppear 等)傳給 B VC.
- B VC 可以拿到 A VC 的 navigationItem 等對象,方便控制.
- B VC 的 view 的 frame 受到 A VC 的控制.
這樣一看好處不少,但是有個坑.
平時Status Bar 的高度是20px, 但是打電話或者錄音的時候再進入 app,Status Bar 高度會變成40px. 這個時候,系統會自動把 UIWindow 的 rootViewController.view 下移20px.
但是不知道為什么,調用addChildViewController以后,B VC 的view 也會下移20px, 這樣以來, StatusBar 高度增加了20px, 但是 B VC 累計向下移動了40px就導致 B VC 與 StatusBar 之間有一個20px 的空隙,并且通話結束后不會恢復.
所以,addChildViewController 以后,還是要手動設置一下 B VC 的 view 的 frame 來避免這個 BUG.
http://stackoverflow.com/questions/17192005/what-does-addchildviewcontroller-actually-do