Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

tab bar click delegate

Tags:

xcode

ios

iphone

I have two view controllers (FirstViewController and SecondViewController) and a Tab Bar Controller and I'm using Storyboards. In the FirstViewController user can drag and drop an imageview. So every time a user clicks on the second TabBarItem which displays the SecondViewController I would like to check if the user has dropped the image or not every time she clicks the TabBarItem.

So I understand that this can be done with UITabBarDelegate and with its method -(void)tabBar:(UITabBar *)tabBar didSelectItem:(UITabBarItem *)item. But I'm doing something wrong because the method isn't called and I believe this is because I can't set the delegate properly. So I want the SecondViewController to be the delegate for TabBarController.

So in my SecondViewController.h I have the following

@interface SecondViewController : UIViewController<UITabBarDelegate>

And in SecondViewController.m I have

-(void)tabBar:(UITabBar *)tabBar didSelectItem:(UITabBarItem *)item {
NSLog(@"%@", item);

}

- (void)viewDidLoad
{
[super viewDidLoad];
self.tabBarController.delegate = self;
}

But nothing happens and when setting the delegate I also get a compiler warning: Assigning to 'id' from incompatible type 'SecondViewController *const __strong'

Please be gentle with me, this is my first app and the first time I'm trying to use delegates.

like image 246
flouwer Avatar asked Dec 09 '22 14:12

flouwer


1 Answers

Add the following code to any of the view controllers

UITabBarController *tabBarController = (UITabBarController*)[UIApplication sharedApplication].keyWindow.rootViewController ;

    [tabBarController setDelegate:self];

// add any delegates methods to your class

-(void)tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController {
    NSLog(@"%@", tabBarController);
}
like image 155
Shams Ahmed Avatar answered Dec 16 '22 09:12

Shams Ahmed