23

我有一个带有故事板的应用程序。我正在使用几个带有 segues 的视图控制器来根据所选项目从表视图中进行选择。我想要一个页面视图控制器,其中页面将是情节提要中的一个或多个视图控制器,甚至重复它们。我正在尝试这样init的页面视图控制器: .... self.dataSource=self;

UIViewController *initialViewController =[self viewControllerAtIndex:current];
NSArray *viewControllers = [NSArray arrayWithObject:initialViewController];


[self setViewControllers:viewControllers direction:UIPageViewControllerNavigationOrientationHorizontal  animated:NO completion:nil];
....

- (UIViewController *)viewControllerAtIndex:(NSUInteger)index
{
if ((descriptions.count == 0) ||
    (index >= descriptions.count)) {
    return nil;
}

current=index;

// Create a new view controller and pass suitable data.
NSString *language = [[NSLocale preferredLanguages] objectAtIndex:0];

Description *description=[DBCompany getDescriptionById:language descriptionId:[[descriptions objectAtIndex:index] integerValue]];

UIViewController *viewController=nil;
if(description.frame==100){
    viewController=[[Company100ViewController alloc] init];
    ((Company100ViewController*)viewController).companyId = companyId;
}
return viewController;
}

- (UIViewController *)pageViewController:(UIPageViewController *)pageViewController viewControllerBeforeViewController:(UIViewController *)viewController
{
if ((descriptions.count == 0) ||
    (current-1 < 0)) {
    return nil;
}

return [self viewControllerAtIndex:current-1];
}

- (UIViewController *)pageViewController:(UIPageViewController *)pageViewController viewControllerAfterViewController:(UIViewController *)viewController
{
if ((descriptions.count == 0) ||
    (current >= descriptions.count)) {
    return nil;
}

return [self viewControllerAtIndex:current+1];
}

然而,它viewcontroller以黑色显示。我认为是因为我正在添加UIviewcontroller类但没有将它连接到任何视图,XIB,在我的故事板的情况下。

如何以编程方式使用情节提要中的不同视图控制器在页面视图控制器中使用?

4

3 回答 3

58

如果您执行 viewController=[[Company100ViewController alloc] init] 那么是的,这不是与情节提要或 XIB 关联的控制器。要使用 XIB 加载控制器,您必须执行以下操作:

UIStoryboard *sb = [UIStoryboard storyboardWithName:@"MainStoryboard" bundle:nil];
Company100ViewController * vc = (Company100ViewController *)[sb instantiateViewControllerWithIdentifier:@"vc-identifier"];

在情节提要中,确保将视图控制器的 id 设置为 vc-identifier;您选择的任何标识符。

于 2013-03-05T01:56:28.860 回答
7

斯威夫特 3

let sb = UIStoryboard(name: "MainStoryboard", bundle: nil)
let vc = sb.instantiateViewController(withIdentifier: "vc-identifier")
于 2017-08-07T14:18:03.473 回答
1

迅速

如果你想从一个UIViewController对象初始化。

guard let vc = storyboard?.instantiateViewController(withIdentifier: "nameVC") else {
  return
}
    
// add to current view
view.addSubview(vc.view)
于 2017-09-22T08:56:53.557 回答