0

I'm pretty new to Objective-C and iOS. I've noticed a familiar pattern in several apps, and I don't understand why it's necessary...

[someParentView addSubview:aChildViewController.view]
[self addChildViewController:aChildViewController]

From what I've read, you're not supposed to mess with a view controllers view directly, but rather just add the child view controller and the parent view controller will decide how and when to consult the childViewController's view.

In other words, when you've added a child viewcontroller to a parent viewcontroller, well obviously the parent viewcontroller has access to the child viewcontroller's view, hence calling addSubview seems not only redundant, but from what I've read, not recommended.

EDIT: Per a question below about more detail of what I'm doing... I have a main storyboard view that covers the whole screen, and then I'm adding a view that takes only the left half of a vertical oriented screen. Users can tap on either the half view I added, or the remaining exposed half on the underlying full screen main storyboard view

  • Are you creating views by code? – vijeesh May 06 '15 at 07:23
  • @iphonic, this is not a duplicate question because I'm asking why addSubview is necessary. Once you've added the childViewController, the parent view controller can access the childViewController's view, hence there should be no need to add it's view manually. –  May 06 '15 at 07:35
  • 1
    @user3457292 You question is well answered in the thread. `addSubView` has nothing to do with `addChildViewController`. – iphonic May 06 '15 at 07:37

2 Answers2

0

Refer the page, it will help you http://www.objc.io/issue-1/containment-view-controller.html

vijeesh
  • 1,317
  • 1
  • 17
  • 32
0

Your main concern as I see is calling addSubview seems redundant?

I would say no it is not redundant, coz addChildViewController just Adds the given view controller as a child but it will not load/add the view. This makes it essential to call addSubview

addSubview Add the child controller’s view as a subview.

For more info see:

Creating Custom Content View Controllers

Implementing a Custom Container View Controller

Vivek Molkar
  • 3,910
  • 1
  • 34
  • 46