08 October 2011

The easier way to create Tabbed Bar in iPhone

I see the easier way to create a UITabBar in iPhone, is through the Controller.

Only create the View yourself, if you want to customize it, otherwise, don't go that way!

Suppose we have a button that we click to open a TabBar with two UITabBarItems, as usual , we push the next controller to the UINavigationConroller ... but this time we will push a UITabBarController..

Here's the code with inline comments:


// create UITabBarController (with its UITabBar view)
UITabBarController* tabController = [[UITabBarController alloc]init];
// create a ref for the first child VC
Tab1ViewContoller* tabVC = [[Tab1ViewContoller alloc]initWithNibName:@"Tab1ViewContoller" bundle:nil];
tabVC.title = @"Tab1 VC"; // the VC title is used also as the title for UITabBarItem in the UITabBar contoller by the above UITabBarController
// create a ref for the second child VC
Tab2ViewContoller* tabVC2 = [[Tab2ViewContoller alloc]initWithNibName:@"Tab2ViewContoller" bundle:nil];
tabVC2.title = @"tab2 VC";
/*** to cusomize the UITabBarItem for each child view controller, set the tabBarItem property of the VC **/
// Optional
property of the VC **/
// Optional
UITabBarItem* tabBarItem1 = [[[UITabBarItem alloc]initWithTitle:nil image:
[UIImage imageNamed:@"icons-word-processor.es"] tag:1] autorelease];
UITabBarItem* tabBarItem2 = [[[UITabBarItem alloc]initWithTitle:@"tab2 item" image:nil tag:2] autorelease];
tabVC.tabBarItem = tabBarItem1;
tabVC2.tabBarItem = tabBarItem2;
//
// create array of ViewContollers to be added to the UITabBarController
NSArray* viewControllers = [NSArray arrayWithObjects:tabVC, tabVC2, nil];
[tabController setViewControllers:viewControllers animated:YES];
// push the UITabBarConrollers (that contains the reference to the 2 VCs to the navigationConroller
[self.navigationController pushViewController:tabController animated:YES];
//release objects in mem
[tabVC2 release];
[tabVC release];
[tabController release];
view raw gistfile1.m hosted with ❤ by GitHub
References:
http://developer.apple.com/library/ios/#DOCUMENTATION/UIKit/Reference/UITabBarController_Class/Reference/Reference.html#//apple_ref/occ/cl/UITabBarController



No comments: