2014-02-07 101 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