简体   繁体   中英

How do I know when a tab bar item is pressed (iOS)

I have 2 view controllers and a tab bar controller created in storyboard.

is it possible to execute a method in either of the 2 view controllers when the relevant tab bar is pressed?

Ive tried several ways but they need a nib name on the firstViewController or secondViewController if I want to initialize an object of the firstViewController, normally the firstViewController is just created on launch,

Any help would be appreciated, I'm vaguely familiar with the uitabcontroller app delegate but I don't know how to hook up the two view controllers to the tab controller

Have a look at the UITabViewController Delegate :

You use the UITabBarControllerDelegate protocol when you want to augment the behavior of a tab bar. In particular, you can use it to determine whether specific tabs should be selected, to perform actions after a tab is selected, or to perform actions before or after the user customizes the order of the tabs. After implementing these methods in your custom object, you should then assign that object to the delegate property of the corresponding UITabBarController object.

All of the methods in this protocol are optional.

Reference : http://developer.apple.com/library/ios/#DOCUMENTATION/UIKit/Reference/UITabBarControllerDelegate_Protocol/Reference/Reference.html


What you need should be achievable by implementing :

- (void)tabBarController:(UITabBarController *)tabBarController 
 didSelectViewController:(UIViewController *)viewController

If you are using storyboard, do this

in didFinishLaunchingWithOptions

UITabBarController *tabBar = (UITabBarController *)self.window.rootViewController;
[tabBar setDelegate:self];

And then

-(void) tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController
{
   //Write your code here
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM