在 UIViewController 视图中的 iOS 嵌套视图控制器视图?

在 iOS 中,在 UIViewController 的视图中嵌套视图控制器的视图是否是典型的不良编程实践?举个例子,我希望有一些互动元素,可以响应用户的触摸,但是只占用了屏幕的25% 。

我想我会把这个嵌套的视图控制器添加到我的 UIViewController 中,比如说:

[self.view addSubview: nestedViewController.view];
64962 次浏览

No, this is generally good design, it helps keep your view controllers concise. However you should be using the view controller containment pattern, take a look at the following documentation.

Implementing a Container View Controller

This is incredibly simple to setup using Interface Builder with Storyboards as well, take a look at the Container View in the object library.

Here is a contrived example in a Storyboard. In this example you would have 4 view controllers, one that holds the 3 containers, and one for each container. When you present the left most controller that has all of the containers, the Storyboard will automatically initialize and embed the other 3. You can access these child view controllers via the childViewControllers property or there is a method you can override prepareForSegue:sender: and capture the destination view controllers of the segue about to be called. This is also a good point to pass properties to the child view controllers if any are needed.

enter image description here

I put this code in the parent view controller. It works great for me.

Obj C

-(void)viewDidLoad{
[super viewDidLoad];
InnerViewController *innerViewController = [self.storyboard instantiateViewControllerWithIdentifier:INNER_VIEW_CONTROLLER];
[self addChildViewController:innerViewController];
[self.view addSubview:innerViewController.view];
[innerViewController didMoveToParentViewController:self];
}

Swift:

 let childViewController = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "ChildViewController"),
self.addChildViewController(childViewController)
self.view.addSubview(childViewController.view)
childViewController.didMove(toParentViewController: self)

Another option is to use IB and put container view. UIViewController will show up automatically (XCode 9 in this case): enter image description here

Here is my Swift 3 solution based on Swift Developers On FB's answer

 let childViewController = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "ChildPageViewController"),
self.addChildViewController(childViewController)
self.view.addSubview(childViewController.view)
childViewController.didMove(toParentViewController: self)