Monday, June 10, 2013

UITabBarItem initWithTabBarSystemItem example in Objective C (iOS).

UITabBarItem initWithTabBarSystemItem

Creates and returns a new item containing the specified system item.

- (id)initWithTabBarSystemItem:(UITabBarSystemItem)systemItem tag:(NSInteger)tag

The system item to use as the first item on the tab bar. One of the constants defined in UITabBarSystemItem.
The receiver’s tag, an integer that you can use to identify bar item objects in your application.

Return Value
A newly initialized item containing the specified system item. The item’s target is nil.

Discussion of [UITabBarItem initWithTabBarSystemItem]
This method returns a system-supplied tab bar item. The title and image properties of the returned item cannot be changed later.

UITabBarItem initWithTabBarSystemItem example.
UITabBarController * tabBarController = [[UITabBarController alloc] init];

UIViewController * viewController1 = [[YourViewController alloc] init];
UIViewController * viewController2 = [[YourOtherViewController alloc] init];

viewController1.tabBarItem = [[UITabBarItem alloc] initWithTabBarSystemItem:UITabBarSystemItemMostViewed tag:0];
viewController2.tabBarItem = [[UITabBarItem alloc] initWithTabBarSystemItem:UITabBarSystemItemMostViewed tag:1];

tabBarController.viewControllers = [NSArray arrayWithObjects:viewController1, viewController2, nil];

Example of [UITabBarItem initWithTabBarSystemItem].
        self.title = NSLocalizedString(@"Liked", @"Liked");
        self.tabBarItem = [[UITabBarItem alloc] initWithTabBarSystemItem:UITabBarSystemItemFavorites tag:0];
        self.tabBarItem.title = @"Liked";

UITabBarItem initWithTabBarSystemItem example.
it's easy to programatically create a tab bar controller:

UITabBarController *tabBarController = [[UITabBarController alloc] init];
[tabBarController setViewControllers:[NSArray arraywithObjects: firstViewController, secondViewController, nil]
And to set the tab bar items:

firstViewController.tabBarItem = [UITabBarItem initWithTabBarSystemItem:UITabBarSystemItemFavorites tag:0];
secondViewController.tabBarItem = [UITabBarItem initWithTabBarSystemItem:UITabBarSystemItemFeatured tag:1];
Then just do whatever you need to do with tabBarController: present it modally (shudder), push it onto a navigation controller (oh god, the humanity), or whatever.

End of UITabBarItem initWithTabBarSystemItem example article.