jctt
jctt

Reputation: 95

Adding UITabBarItem to UITabBar programmatically, and set action to it

I'm working with iOS 6.1 and I have a TabBarController with two Items, each of them are pushing to a NavigationControllerView.

How can I add a new UITabBarItem to the TabBarController, from any of the child controllers, and set an specific action.

Note: Now I revised several questions asked in StackOverflows with almost identical phrasing than this one, however their implementation is not quite as I'm describing here.

Is this allowed in iOS? If not, will you share your thoughts of how you would do it?

Note: after a few days of bumping I tried the following approach, It worked, but I don't feel entirely comfortable with it.

The approach consist of having one of your controller class,

1) Have one of your controller class to inherit the UITabBarControllerDelegate. In my case I implemented this delegate in the class that will be most likely to be instantiated for the first time after the AppDelegate, in other words the Class that belongs to the first view of the app, for example

interface MainTableViewController: UITableViewController <UITabBarControllerDelegate>
...

2) Set the delegate of the TabBarController in viewDidLoad

self.tabBarController.delegate = self;

3) Implement the protocol tabBarController:shouldSelectViewController:, using this method you can control which view will be shown.

In my case, I previously added a few dummy viewcontrollers and I gave to each BarItem a different tag number

- (BOOL)tabBarController:(UITabBarController *)tabBarController shouldSelectViewController:(UIViewController *)viewController
{
    switch (viewController.tabBarItem.tag) {
        case 3:
        {
            [self someActionA];
            return NO;
        }
        case 4:
        {
            [self someActionB];
            return NO;
        }
        default:
            return YES;
    }
}

So far this code will do the trick of what I really intended in the first place, however I wish I could've done this in the AppDelegate.

In the case someone might come across with the same issue, or if you have a different approach please do share.

Upvotes: 0

Views: 539

Answers (1)

NevzatR
NevzatR

Reputation: 165

You can create new controller using Inheritence from UITabBarController and add a custom button on UITabBar --> UITabBarItem therefore UITabBarItem send to back and your custom button shown front. You can set any spesific action with this custom button. Otherwise iOS SDK does not allow giving a spesific action for UITabBarItem.

Upvotes: 1

Related Questions