如何从故事板中的NIB子视图转换为视图控制器

时间:2013-08-14 16:01:24

标签: ios storyboard segue nib

我有一个故事板和NIB视图控制器的组合,我怎样才能从一个到另一个呢?

这是场景:

         UITabBarController(storyboard)|- UINavigationController (subclassed in storyboard) -> [UIViewController (NIB)] -> UIViewController (in Storyboard)

2 个答案:

答案 0 :(得分:2)

您必须在故事板中为UIViewController提供“故事板ID”(在“身份检查器”标签中)。然后在NIB ViewController的代码中实例化ViewController,如下所示:

UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"MainStoryboard" bundle:nil];

ViewController *vc = [storyboard instantiateViewControllerWithIdentifier:@"YourViewControllerId"];
[self.navigationController pushViewController:vc animated:YES]; 

答案 1 :(得分:1)

在您的UINavigationController子类中,您需要使用NIB中的视图实例化视图控制器(让我们称之为NIBViewController)并使用方法setViewControllers:animated:将该视图控制器设置为rootViewController。在awakeFromNib这样做:

- (void)awakeFromNib
{
    [super awakeFromNib];

    NIBViewController *viewController = [[NIBViewController] init];// It will look for the appropriate XIB as long as you did not change its name and it's in the main bundle, otherwise use initWithNibName:bundle:

    [self setViewControllers:@[viewController] animated:NO];
}

然后,从NIBViewController转到故事板中包含的其他视图控制器,只需在该视图控制器的故事板中设置一个标识符,然后根据需要实例化并推送或显示它。

重要的是要在NIBViewController实例中标记self.storyboard将为nil,因为该视图控制器不包含在故事板中,因此您需要实例化新的故事板(解决方案A **)或从中获取故事板导航控制器(解决方案B):

// Solution A
UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"MainStoryboard" bundle:nil];

// Solution B
UIStoryboard *storyboard = [self.navigationController storyboard];

UIViewController *storyboardViewController = [storyboard instantiateViewControllerWithIdentifier:@"viewControllerId"];

[self.navigationController pushViewController:storyboardViewController animated:YES];

**请注意,这是创建故事板的新实例,因此最好不要尝试棘手的事情并避免与故事板中包含的先前视图控制器发生隔离,否则您会发现这些视图控制器不同。 ..这是我想到的第一个解决方案,但绝对应该选择解决方案B.