2014-02-07 37 views
0

我想编写一个创建ViewControllers的应用程序。可能吗?以编程方式/自动创建ViewControllers

现在我正在做一个tabbar,它从网站获取一个随机数(n)并创建n个选项卡。当我运行应用程序时,它都可以,但是当我点击一个选项卡时,它会失败而不显示错误。我怎么做到的?

这里的是一个简单的代码,我使用的是哪里的网页是我想要的选项卡数的数组:

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]; 

我不知道这是否是可能的,或者我怎么能做到这一点,任何帮助将受到欢迎。

谢谢!

回答

1

是非常可能的,

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

这是你是如何做的(我的例子是在didFinishLaunching中的appDelegate)

不正确的方法

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视图作为子视图添加到其他视图。

正确的方法(也didFinishLaunching中的appDelegate)

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视图的子视图。

+0

谢谢!它解决了崩溃!现在我的观点全是黑色的......我要解决它!非常感谢! –

+0

很高兴我能帮上忙 – anders