通过方法有条件地显示视图控制器

时间:2015-08-21 22:58:38

标签: ios objective-c segue uistoryboardsegue

我有一个分为不同途径的类,我想通过创建一个有条件地隔离VC的方法尽可能地减少代码。但我

-(void)segueToViewController {

}

但我不知道如何使用其他视图控制器进行子类化。

通常你会这样做:

UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
SignInViewController *signInVC = [storyboard instantiateViewControllerWithIdentifier:@"SignInViewController"];
[self presentViewController:signInVC animated:NO completion:nil];

但是如果我们不知道segueToViewController的班级名称怎么办?我已经尝试了很多东西,但无法弄明白。你可能会为此投票给我,但无论如何都能得到解决方案。至少我已经尝试过这个了。我首先要说我对UIViewController的ID差异的基本知识很少:

-(void)segueToViewController:(id)viewController {
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
    viewController = [storyboard instantiateViewControllerWithIdentifier:@"someVCID"];
    [self presentViewController:viewController animated:NO completion:nil];
}

这个问题是因为我的按钮会从n个类中选择一个随机类进行实例化,所以我想在一个方法中保持简单如上所述,而不是长if conditionswitch method / p>

2 个答案:

答案 0 :(得分:0)

例如,您可以拥有一个数组,其中包含您要选择的视图控制器的所有故事板标识符。然后你随机选择其中一个并致电:

    - (void)segueToViewControllerWithIdentifier:(NSString *)identifier
    {
        UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
        UIViewController *viewController = [storyboard instantiateViewControllerWithIdentifier:identifier];
        [self presentViewController:viewController animated:NO completion:nil];
    }

答案 1 :(得分:0)

    You can do with the segue identifier.

    - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Make sure your segue name in storyboard is the same as this line
    if ([[segue identifier] isEqualToString:@"Segue Name Here"])
    {
        // Get reference to the destination view controller
        YourViewController *vc = [segue destinationViewController];

        // Pass any value or object to the view controller here, like
        [vc setObject:object];
    }
}