Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create uiTabBarController programmatically

I want to create a UIView for a UITabBarController

Here is my code for the .h file :

@interface TE : UIViewController <UITabBarControllerDelegate>{
    UITabBarController *tabBarController;
}
@property (nonatomic,retain) UITabBarController *tabBarController;
@end

The viewDidLoad method:

UIViewController *testVC = [[T1 alloc] init];
UIViewController *otherVC = [[T2 alloc] init];
NSMutableArray *topLevelControllers = [[NSMutableArray alloc] init];
[topLevelControllers addObject: testVC];
[topLevelControllers addObject: otherVC];
tabBarController = [[UITabBarController alloc] init];
tabBarController.delegate = self;
[tabBarController setViewControllers:topLevelControllers animated:NO];
tabBarController.selectedIndex = 0;
self.view = tabBarController.view;

This creates the tab bar controller, but when I click on a tab bar item, I get an error:

Thread1:Program receive signal: SIGABRT

Edit: I solved the problem by downloading and modifying the version of http://www.iphonedevcentral.com/create-uitabbarcontroller/

like image 290
Mehdi Avatar asked Nov 17 '11 08:11

Mehdi


2 Answers

You say above that you don't want to create the tabBarController in the appDelegate. Why not? Where else would you create it? The tabBarController has to be the root view controller and cannot be a child of any other view controller.

Btw, make sure you implement:

- (BOOL)tabBarController:(UITabBarController *)tabBarController shouldSelectViewController:(UIViewController *)viewController {

    NSUInteger tabIndex = [tabBarController.viewControllers indexOfObject:viewController];

    if (viewController == [tabBarController.viewControllers objectAtIndex:tabIndex] ) {
         return YES;
    }

    return NO;

}
like image 182
ader Avatar answered Sep 20 '22 20:09

ader


  1. Subclass UITabBarController

  2. Override the - (void) loadView method and include the following code

    MyCustomViewControllerOne* ctrl1 = [[[MyCustomViewControllerOne alloc] initWithNibName@"MyViewControllerOne" bundle: nil] autorelease];
    UIViewController* ctrl2 = [[[UIViewController alloc] init] autorelease];
    MyCustomControllerTwo* ctrl3 = [[[UIViewController alloc] initWithObject: myObj] autorelease];
    
    ctrl1.title = @"First tab";
    ctrl2.title = @"Second tab";
    ctrl3.title = @"Third tab";
    
    ctrl1.tabBarItem.image = [UIImage imageNamed:@"tab_image1.png"];
    ctrl2.tabBarItem.image = [UIImage imageNamed:@"tab_image2.png"];
    ctrl3.tabBarItem.image = [UIImage imageNamed:@"tab_image3.png"];
    
    [self setViewControllers: @[ctrl1, ctrl2, ctrl3]];
    

That's pretty much it.

like image 32
bbrame Avatar answered Sep 18 '22 20:09

bbrame