简体   繁体   English

在子视图中添加 UIViewController

[英]add UIViewController in subview

I don't know if this is the right key to search "add UIViewController in subview".我不知道这是否是搜索“在子视图中添加 UIViewController”的正确键。 As what you can see in my image ,there are two ViewController, the main and the second controller.正如你在我的图片中看到的,有两个 ViewController,主控制器和第二控制器。 Inside the main controller there is a UIView(blue background color).在主控制器内部有一个 UIView(蓝色背景色)。 Inside in UIView, I want to add the second ViewController in my UIView.在 UIView 中,我想在 UIView 中添加第二个 ViewController。 I have this code but It didn't work.我有这个代码,但没有用。

在此处输入图片说明

here's my code这是我的代码

#import "ViewController.h"
#import "SampleViewController.h"
@interface ViewController ()
@property (weak, nonatomic) IBOutlet UIView *testView;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    SampleViewController * sample = [[SampleViewController alloc] initWithNibName:@"SampleViewController" bundle:nil];
    sample.view.frame = CGRectMake(0, 0, self.testView.bounds.size.width, self.testView.bounds.size.height);
    [self.testView addSubview:sample.view];
} 

@end

I want to know if this is possible?我想知道这是否可能? I know initWithNibName: works in xib file, I don't the exact term to search in google about this.我知道initWithNibName:在 xib 文件中工作,我不知道在谷歌中搜索这个的确切术语。 I'm just trying to experiment something if this is possible in IOS.如果这在 IOS 中可行,我只是想尝试一些东西。 Hoping you understand what I'm trying to do.希望你明白我在做什么。 Hoping for your advice.希望得到您的建议。 Thanks in advance提前致谢

here's my update这是我的更新

@interface ViewController ()
@property (weak, nonatomic) IBOutlet UIView *testView;
@property(strong,nonatomic) SampleViewController * samples;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

UIStoryboard *storyBoard = self.storyboard;
SampleViewController * sample = [storyBoard instantiateViewControllerWithIdentifier:@"SampleViewController"]; 
// SampleViewController * sample = [[SampleViewController alloc] //initWithNibName:@"SampleViewController" bundle:nil];

[self displayContentController:sample];
//commented the below line because it is not needed here, use it when you want to remove        
//child view from parent.
 //[self hideContentController:sample];

}

- (void) displayContentController: (UIViewController*) content;
{
    [self addChildViewController:content];                 // 1
    content.view.bounds = self.testView.bounds;                 //2
    [self.testView addSubview:content.view];
    [content didMoveToParentViewController:self];          // 3
}


- (void) hideContentController: (UIViewController*) content
{
    [content willMoveToParentViewController:nil];  // 1
    [content.view removeFromSuperview];            // 2
    [content removeFromParentViewController];      // 3
}

I always get this error我总是收到这个错误

Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Could not load NIB in bundle: 'NSBundle </Users/ace/Library/Developer/CoreSimulator/Devices/035D6DD6-B6A5-4213-9FCA-ECE06ED837EC/data/Containers/Bundle/Application/EB07DD14-A6FF-4CF5-A369-45D6DBD7C0ED/Addsubviewcontroller.app> (loaded)' with name 'SampleViewController''

I think, its looking for a nib.我想,它在寻找一个笔尖。 I didn't implement a nib here.我没有在这里实现笔尖。

You should use Child containment concept, here MainViewController is a parent view controller and you want to add child view controller view as a subview on Main View Controller.您应该使用子包含概念,这里 MainViewController 是一个父视图控制器,您希望将子视图控制器视图添加为主视图控制器上的子视图。

Adding and Removing a Child添加和删​​除子项

//call displayContentController to add SampleViewCOntroller view to mainViewcontroller
 [self displayContentController:sampleVCObject];

// write this method in MainViewController
- (void) displayContentController: (UIViewController*) content;
{
   [self addChildViewController:content];                 // 1
   content.view.bounds = testView.bounds;                 //2
   [testView addSubview:content.view];
   [content didMoveToParentViewController:self];          // 3
}

Here's what the code does:下面是代码的作用:

It calls the container's addChildViewController: method to add the child.它调用容器的 addChildViewController: 方法来添加孩子。 Calling the addChildViewController: method also calls the child's willMoveToParentViewController: method automatically.调用 addChildViewController: 方法也会自动调用孩子的 willMoveToParentViewController: 方法。 It accesses the child's view property to retrieve the view and adds it to its own view hierarchy.它访问子视图属性以检索视图并将其添加到自己的视图层次结构中。 The container sets the child's size and position before adding the view;容器在添加视图之前设置孩子的大小和位置; containers always choose where the child's content appears.容器总是选择子内容出现的位置。 Although this example does this by explicitly setting the frame, you could also use layout constraints to determine the view's position.尽管本示例通过显式设置框架来实现这一点,但您也可以使用布局约束来确定视图的位置。 It explicitly calls the child's didMoveToParentViewController: method to signal that the operation is complete.它显式调用子节点的 didMoveToParentViewController: 方法来发出操作完成的信号。

//you can also write this method in MainViewController to remove the child VC you added before.
- (void) hideContentController: (UIViewController*) content
{
   [content willMoveToParentViewController:nil];  // 1
   [content.view removeFromSuperview];            // 2
   [content removeFromParentViewController];      // 3
}

For more details, please refer to apple doc: https://developer.apple.com/library/content/featuredarticles/ViewControllerPGforiPhoneOS/ImplementingaContainerViewController.html更多详情请参考苹果文档: https : //developer.apple.com/library/content/featuredarticles/ViewControllerPGforiPhoneOS/ImplementingaContainerViewController.html

Configuring a Container in Interface Builder, for those who don't want to write code.在 Interface Builder 中配置一个容器,适合那些不想写代码的人。

To create a parent-child container relationship at design time, add a container view object to your storyboard scene, as shown in Figure 5-3.要在设计时创建父子容器关系,请将容器视图对象添加到故事板场景中,如图 5-3 所示。 A container view object is a placeholder object that represents the contents of a child view controller.容器视图对象是一个占位符对象,表示子视图控制器的内容。 Use that view to size and position the child's root view in relation to the other views in the container.使用该视图来调整与容器中其他视图相关的子级根视图的大小和位置。

在 Interface Builder 中添加容器视图 When you load a view controller with one or more container views, Interface Builder also loads the child view controllers associated with those views.当你加载一个带有一个或多个容器视图的视图控制器时,Interface Builder 也会加载与这些视图关联的子视图控制器。 The children must be instantiated at the same time as the parent so that the appropriate parent-child relationships can be created.子项必须与父项同时实例化,以便可以创建适当的父子关系。

You can do this simply by using StoryBoards您只需使用 StoryBoards 即可完成此操作

  • Open storyboards and select the view controller in which your Blue view is present, open Utilities search for ContainerView and drag it into your blue view, this will automatically adds an view controller that acts as child view for your view.打开故事板并选择您的蓝色视图所在的视图控制器,打开实用程序搜索 ContainerView 并将其拖到您的蓝色视图中,这将自动添加一个视图控制器作为您的视图的子视图。 You can resize your container view in size inspector.您可以在大小检查器中调整容器视图的大小。

在此处输入图片说明

I've resolved the problem about the uiview on second uiviewcontroller.我已经解决了关于第二个 uiviewcontroller 上的 uiview 的问题。 Follow the code that I've used:按照我使用过的代码:

    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
SecondViewController *sb = (SecondViewController *)[storyboard instantiateViewControllerWithIdentifier:@"sb"];

sb.view.backgroundColor = [UIColor redColor];    
[sb willMoveToParentViewController:self];

[self.view addSubview:sb.view];

[self addChildViewController:sb];
[sb didMoveToParentViewController:self];

I hope to help you.我希望能帮助你。

Thanks a lot非常感谢

You can add a childViewController to UIViewController since iOS5.. it is a great way to maker smaller, more reusable viewControllers, I also really like it.从 iOS5 开始,您可以向 UIViewController 添加 childViewController ..这是制作更小、更可重用的 viewController 的好方法,我也非常喜欢它。

you're really close, but you just need a couple more lines of code..你真的很接近,但你只需要多几行代码..

///
 [self addChildViewController:sample];

 [self.testView addSubview:sample.view]; //you already have this..

 [sample didMoveToParentViewController:self]; 

In you viewWillDisappear: or one of the other teardown methods you'll need to clean up like this:在您 viewWillDisappear: 或您需要像这样清理的其他拆卸方法之一:

//we'll need another pointer to sample, make it an iVar / property..
   [sample willMoveToParentViewController:nil];  // 1
   [sample removeFromSuperview];            // 2
   [sample removeFromParentViewController];      // 3

You can read the Apple docs on containing child viewControllers here https://developer.apple.com/library/ios/featuredarticles/ViewControllerPGforiPhoneOS/CreatingCustomContainerViewControllers/CreatingCustomContainerViewControllers.html您可以在此处阅读有关包含子视图控制器的 Apple 文档https://developer.apple.com/library/ios/featuredarticles/ViewControllerPGforiPhoneOS/CreatingCustomContainerViewControllers/CreatingCustomContainerViewControllers.html

SampleViewController * sample = [[SampleViewController alloc] initWithNibName:@"SampleViewController" bundle:nil];
sample.view.frame = CGRectMake(0, 0, self.testView.bounds.size.width, self.testView.bounds.size.height);

[self addChildViewController:sample];
[self.testView addSubview:sample.view];

I'm tring to adding UIViewController in subview, and this work.我正在尝试在子视图中添加 UIViewController,这项工作。 On UIViewController I've added 2 button, in .h file:在 UIViewController 上,我在 .h 文件中添加了 2 个按钮:

-(IBAction)matchButtonAction:(id)sender;
-(IBAction)closeButtonAction:(id)sender;

And in .m file:在 .m 文件中:

-(IBAction)matchButtonAction:(id)sender
{
    NSLog(@"matchButtonAction");
}
-(IBAction)closeButtonAction:(id)sender
{
    NSLog(@"closeButtonAction");
}

but I don't see the log.但我没有看到日志。

I need to add same parameter on UIViewController instantiateViewControllerWithIdentifier?我需要在 UIViewController instantiateViewControllerWithIdentifier 上添加相同的参数吗?

How to resolve the problem?如何解决问题?

My UIViewController initialization is:我的 UIViewController 初始化是:

AlertDialogViewController *alertDialogView = (AlertDialogViewController *)[self.storyboard instantiateViewControllerWithIdentifier:@"alertDialogView"];         
        [alertDialogView willMoveToParentViewController:self];
        [viewController.view addSubview:alertDialogView.view];
        [viewController addChildViewController:alertDialogView];
        [alertDialogView didMoveToParentViewController:viewController];

Since your view controller is in storyboard you should use instantiateViewControllerWithIdentifier to get the VC from storyboard.由于您的视图控制器在情节提要中,因此您应该使用instantiateViewControllerWithIdentifier从情节提要中获取 VC。

SampleViewController * sample = [self.storyboard instantiateViewControllerWithIdentifier:@"IdOfSampleViewController"];
sample.view.frame = CGRectMake(0, 0, self.testView.bounds.size.width, self.testView.bounds.size.height);
[self.testView addSubview:sample.view];

Don't forget the add the identifier for the SampleViewController in storyboard不要忘记在故事板中为SampleViewController添加标识符

I've try to use this code:我尝试使用此代码:

SecondViewController *secondViewController = [[SecondViewController alloc] initWithNibName:nil bundle:nil]; SecondViewController *secondViewController = [[SecondViewController alloc] initWithNibName:nil bundle:nil];

 secondViewController.view.frame = CGRectMake(0, 0, self.mySubView.bounds.size.width, self.mySubView.bounds.size.height);

 [self addChildViewController:secondViewController];
 [self.viewDialogSolution addSubview:secondViewController.view];

but I see only myview not the layout of secondViewController.但我只看到 myview 而不是 secondViewController 的布局。

Ho to resolve the probleam?何来解决问题?

Thanks a lot非常感谢

let controller:SecondViewController = self.storyboard!.instantiateViewController(withIdentifier: "secondViewController") as!让 controller:SecondViewController = self.storyboard!.instantiateViewController(withIdentifier: "secondViewController") as! SecondViewController第二个视图控制器

controller.view.frame = self.view.bounds controller.view.frame = self.view.bounds

controller.willMove(toParent: self) controller.willMove(toParent: self)

self.view.addSubview(controller.view) self.view.addSubview(controller.view)

self.addChild(controller) self.addChild(控制器)

controller.didMove(toParent: self) controller.didMove(toParent: self)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 将UIViewController添加为UIScrollView的子视图 - Add UIViewController as subview of UIScrollView 在 UIViewController 中添加 Storyboard 作为子视图 - Add Storyboard as subview in UIViewController 将子视图添加到UIImageView,它是IB中UIViewController的视图出口 - Add a subview to a UIImageView that is the view outlet of a UIViewController in IB 如何添加子视图来覆盖UINavigation barin UIViewController? - How to add a subview to cover UINavigation barin UIViewController? 如何将UIViewController的视图作为子视图添加到UITableViewCell? - How to add a UIViewController's view as a subview to a UITableViewCell? 在自定义UITableViewCell的子视图中添加UIViewController - Add UIViewController inside a Subview of custom UITableViewCell 将UIViewControllers视图添加为另一个UIViewController视图的子视图 - Add UIViewControllers View as a subView of another UIViewController view MyScript如何在另一个UIViewController内将mathwidget添加为子视图 - MyScript how to add mathwidget as a subview inside another UIViewController 将UIViewController添加到子视图并将其删除的最正确方法是什么? - What is the most correct way to add a UIViewController to a subview and remove it? 在情节提要中向从nib加载的自定义类UIViewController添加子视图 - Add a subview to a custom class UIViewController that loads from nib, in Storyboard
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM