我不确定这是否是正确的关键词来搜索“将UIViewController添加到子视图中”。
如图所示,我的应用程序有两个ViewController,一个是主ViewController,另一个是第二ViewController。在主ViewController中,有一个UIView(蓝色背景)。我想在UIView中添加第二个ViewController。我有以下代码,但它没有起作用。
这是我的代码:
#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
我想知道这是否可能?我知道initWithNibName:
可以在xib文件中使用,但不知道在谷歌上搜索相关术语。我只是想尝试在IOS中实验一些东西,希望你能理解我的意图。希望得到你的建议。提前致谢。
这是我的更新。
@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
}
我总是遇到这个错误
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''
我认为它正在寻找一个nib文件。我这里没有实现一个nib。