加载从故事板中实例化的nib文件

时间:2012-06-04 17:37:50

标签: iphone objective-c ios ipad

所以我对这个故事板概念很新。我有一个视图nibs放入故事板,每个对应一个UIViewController子类,我尝试使用以下代码加载nib文件:

TestViewController *vc = [[TestViewController alloc] initWithNibName:@"TestViewController" bundle:nil];
    [self.view setBackgroundColor:[UIColor blueColor]];
    [self.view setFrame:CGRectMake(0, self.profilePicture_.frameHeight + self.profilePicture_.frameY + 10, self.scrollView_.frameWidth, 100)];
    [self.view addSubview:vc.view];

但是,它给了我以下错误:

*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Could not load NIB in bundle: 'NSBundle </Users/aditya15417/Library/Application Support/iPhone Simulator/5.1/Applications/64E6CEC9-E6DC-4AF5-BF16-11BFB6415BDC/Pulse.app> (loaded)' with name 'TestViewController''

所以问题是,如果我在故事板中有我的笔尖,是不是可以使用initWithNibName?如果有办法,我该怎么做?

4 个答案:

答案 0 :(得分:7)

请使用

[self.storyboard instantiateViewControllerWithIdentifier:@"some identifier you set in IB"];

答案 1 :(得分:0)

为什么要将PNRNewsfeedViewController加载为TestViewController? TestViewController是PNRNewsfeedViewController的基类吗?确保在nib中,File's Owner自定义类设置为PNRNewsfeedViewController,然后分配新闻源视图控制器:

PNRNewsfeedViewController *vc = [[PNRNewsfeedViewController alloc] initWithNibName:@"PNRNewsfeedViewController" bundle:nil];
// ...

答案 2 :(得分:0)

使用故事板时,不直接使用单个nib,也不自行实例化视图控制器。您可以使用UIStoryboard类从故事板as described in the documentation实例化视图控制器。

答案 3 :(得分:0)

这就是我的方式:

UIStoryboard *storyBoard = [UIStoryboard storyboardWithName:@"MainStoryboard" bundle:[NSBundle mainBundle]];