addChildViewController 的作用以及 BUG

蘋果的文檔是這樣說的:

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.

這樣做有幾個好處:

  1. 在 A VC 參與 ViewController 跳轉的時候,可以把生命周期回調(viewDidLoad viewWillAppear 等)傳給 B VC.
  2. B VC 可以拿到 A VC 的 navigationItem 等對象,方便控制.
  3. 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

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容