Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
510 views
in Technique[技术] by (71.8m points)

ios - Add a child view controller's view to a subview of the parent view controller

I want to add a tableViewController as a child view controller of a containerViewController (shown below). According to Apple's View Controller Programming Guide I can achieve this by the following lines of code inside my containerViewController:

   [self addChildViewController:tableViewController];
   [self.view addSubview:tableViewController.view];
   [tableViewController didMoveToParentViewController:self];

In fact, that works fine. Now the problem is that I do not want to add the tableViewController's view as a subview of the containerViewController's root view. Instead I want to add it as a subview of the containerView (see image) which itself is a subview of the containerViewController's root view. So I changed the above code as follows:

   [self addChildViewController:tableViewController];
   [self.contentView addSubview:tableViewController.view];
   [tableViewController didMoveToParentViewController:self];

Now when I launch the app it crashes immediately with this error:

Terminating app due to uncaught exception 'UIViewControllerHierarchyInconsistency', reason: 'child view controller: should have parent view controller: but actual parent is:'

What is the problem here? Is it not possible to add a childViewController's view to a specific sub view of its containerViewController? Or how can I achieve this without an error in the view controller hierarchy?

containerViewController

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It doesn't really matter which view you are adding the child viewController to. If a view of a viewController is added to another viewController you need set it properly.

tableViewController.view.frame = self.contentView.bounds;
[self.contentView addSubview:tableViewController.view];
/*Calling the addChildViewController: method also calls 
the child’s willMoveToParentViewController: method automatically */
[self addChildViewController:tableViewController];
[tableViewController didMoveToParentViewController:self];

Source code


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...