【问题标题】:Create ViewControllers programmatically/automatically以编程方式/自动创建 ViewController
【发布时间】:2014-02-07 19:17:46
【问题描述】:

我想编写一个自己创建 ViewControllers 的应用程序。有可能吗?

现在我正在做一个从网站获取随机数(n)并创建 n 个标签的标签栏。当我运行该应用程序时一切正常,但是当我点击一个选项卡时它会失败而不会显示错误。我怎样才能做到?

这是我正在使用的简单代码,其中 pages 是一个包含我想要的选项卡数量的数组:

NSMutableArray* controllers = [[NSMutableArray alloc] init];

    for (int i=0; i<[pages count]; i++) {

        UIViewController * vc1 = [[UIViewController alloc] init];

        vc1.title = [[pages objectAtIndex:i] objectForKey:@"title"];
        [controllers addObject:vc1];
    }

    tabBarController.viewControllers = controllers;

    [_window addSubview:tabBarController.view];

我不知道这是否可能或如何做到,欢迎任何帮助。

谢谢!!!

【问题讨论】:

    标签: ios ios7 uiviewcontroller uitabbarcontroller


    【解决方案1】:

    是的,很有可能,

    您遇到的问题是将 tabBarController “添加到视图”的方式。我能够复制你的崩溃错误,就像你说的那样,没有给出有用的警告。

    这就是你的做法(我的例子是在 appDelegate 中的 didFinishLaunching 中)

    错误的方式

    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    self.window.backgroundColor = [UIColor whiteColor];
    [self.window makeKeyAndVisible];
    
    UIViewController *vc = [[UIViewController alloc] init];
    [vc.view setFrame:self.window.frame];
    
    UITabBarController *tabBarController = [[UITabBarController alloc] init];
    NSMutableArray* controllers = [[NSMutableArray alloc] init];
    
    for (int i=0; i<10; i++) {
    
        UIViewController * vc1 = [[UIViewController alloc] init];
    
        vc1.title = [NSString stringWithFormat:@"%d", i];
        [controllers addObject:vc1];
    }
    
    [tabBarController setViewControllers:controllers];
    
    self.window.rootViewController = vc;
    
    [vc.view addSubview:tabBarController.view];
    return YES;
    

    正确的方法是将 tabBarController 设置为 windows rootViewController,而不是将 tabBarControllers 视图作为子视图添加到其他视图。

    正确的方式(也在 appDelegate 中的 didFinishLaunching 中)

    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    self.window.backgroundColor = [UIColor whiteColor];
    [self.window makeKeyAndVisible];
    
    UITabBarController *tabBarController = [[UITabBarController alloc] init];
    NSMutableArray* controllers = [[NSMutableArray alloc] init];
    
    for (int i=0; i<10; i++) {
    
        UIViewController * vc1 = [[UIViewController alloc] init];
    
        vc1.title = [NSString stringWithFormat:@"%d", i];
        [controllers addObject:vc1];
    }
    
    [tabBarController setViewControllers:controllers];
    
    self.window.rootViewController = tabBarController;
    return YES;
    

    希望这能让您走上正轨。这里的要点是您不应该尝试将 viewControllers 视图作为子视图添加到其他 viewControllers 视图中。

    【讨论】:

    • 谢谢!它解决了崩溃!现在我的观点全是黑色的......我要解决它!非常感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-20
    相关资源
    最近更新 更多