Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to add UITabBarItem programmatically?

In my application, i have added UITabBarController in "Storyborad". But now i want to add UITabBarItem programmatically. Let's say there are 5 buttons and when ever user click on that button my UITabBarController is called. There are total 5 tab in "tabbar". e.g:

Tab name:item1,item2,item3,item4,item5. Button name:item1,item2,item3,item4,item5.

Let's say user click on item1 button, UITabBarcontroller is called. Now user should not be able to see that item1 tab in "tabbarcontroller", he should be able to see the reset "tabBaritem".

Can anyone help me out with this? How to do it programmatically?

Thanks.

Nilesh J

like image 688
Nilesh .S. Joshi Avatar asked Oct 21 '22 08:10

Nilesh .S. Joshi


2 Answers

UITabBarItem * itemNew = [[UITabBarItem alloc] initWithTitle:@"Page 1"
                                                     image:[UIImage imageNamed:@"page1_image_normal"]
                                             selectedImage:[UIImage imageNamed:@"page1_image_selected"]];

Get existing tabBarItems

NSMutableArray *tbItems = [NSMutableArray arrayWithArray:[self.tabBar items]];
//Add your new tabBarItem
[tbItems addObject:itemNew];

//Set your tabBar items to the new array
[self.tabBar setItems:tbItems];

Swift 4

if var controllers = tabBarController?.viewControllers {
   let tabItem = UITabBarItem(title: "Item \(controllers.count)", image: nil, selectedImage: nil)
   let vc = UIViewController() // your new view controller
   vc.tabBarItem = tabItem
   controllers.append(vc) // or insert at index up to you
   tabBarController?.setViewControllers(controllers, animated: true)
}
like image 149
Pancho Avatar answered Oct 23 '22 01:10

Pancho


To call tabBar click event you need to do the following:

call delegatemethod on UITabBarDelegate and implement their method:

- (void)tabBar:(UITabBar *)tabBar didSelectItem:(UITabBarItem *)item {
    //self.tabBarItem.title = @"Title";
}
like image 26
Abhishek Verma Avatar answered Oct 23 '22 02:10

Abhishek Verma