David Biga David Biga - 3 months ago 13
Objective-C Question

Checking when a TabBar item is clicked - Objective C

I have a

ViewController
with 2
sub containers
. The first
sub container
points to a
ViewController
with a
TabBar
inside it. The second
sub container
is a
ViewController
that contains a
collection view
. Now my issue is trying to access the first
sub containers
TabBar
so that when an Item is clicked, I can know which item is clicked and process my data.

The main
ViewController
has a class. All the other
sub containers
for that
ViewController
also have a class. Here is the
.h
for my
sub container
with the
Tab Bar
:

#import <UIKit/UIKit.h>


@interface home_tab : UIViewController <UITabBarControllerDelegate>{

}
@end


.m
:

- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
-(void) tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController
{
NSLog(@"working");

}


Now when clicking on the
Tab Bar
that is populated,
didSelectViewController
is never called.

I am using storyboard.

Suggestions and thoughts?

Answer

I think you have a couple problems atleast from what I can see here,

  1. You are using a TabBar inside of a ViewController, not a UITabBarController, thus you need to use UITabBarDelegate not UITabBarControllerDelegate. You will have to manage the view controllers or whatever view you will want to be loaded on your own most likely with the delegate callback:

    -(void)tabBar:(UITabBar *)tabBar didSelectItem:(UITabBarItem *)item;

Also you dont have a UITabBar defined in your controller, therefore your ViewController has no idea you have a UITabBar in your Storyboard. You need something like this:

    @interface ViewController : UIViewController <UITabBarDelegate>

    @property (weak, nonatomic) IBOutlet UITabBar *tabBar;

    @end

Then you will need to Control drag from the ViewController to your UITabBar and back to connect the Delegate in your Storyboard.

Id recommend using a UITabBarController so you dont have to manage the views yourself depending on what you are trying to accomplish.

Hope this helps!

Comments