Robert
Robert

Reputation: 5302

UITabBarButton without switching to another view

Does anyone know of a way to have a UITabBarButton that, rather than segueing to another view controller, will perform another function, e.g. call a method?

My iPad app utilises a tab bar but the client wants the right-most button to perform a check for updates on a server; however I can't seem to to figure out how to have a button that won't switch views when pressed. I tried deleting the segue but that removes the button as well.

-EDIT- screenshot and code snippet added for clarity. The tab labelled Sync is the one I want not to open a viewController:

enter image description here

AppDelegate.h:

@interface AppDelegate : UIResponder <UIApplicationDelegate, UITabBarControllerDelegate>

@property (strong, nonatomic) UIWindow *window;
@property (strong, nonatomic) UIViewController *viewController;

@end

AppDelegate.m

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    [self.window makeKeyAndVisible];       
    UITabBarController *tabBarController = (UITabBarController *)self.window.rootViewController;
    tabBarController.delegate = (id)self;

   [[NSNotificationCenter defaultCenter] addObserver:self  selector:@selector(applicationDidTimeout:) name:kApplicationDidTimeoutNotification object:nil];

    return YES;
}

and:

- (BOOL)tabBarController:(UITabBarController *)tabBarController shouldSelectViewController:(UIViewController *)viewController {

    NSLog(@"vc = %@", viewController);
    return YES;
}

Upvotes: 0

Views: 944

Answers (1)

Yaman
Yaman

Reputation: 3991

Look at the UITabBarControllerDelegate method :

– tabBarController:shouldSelectViewController:

If selectViewController == your last tab bar, return NO and perform others actions

EDIT :

Look at the example I've made :

AppDelegate.h

@interface ISAppDelegate : UIResponder <UIApplicationDelegate, UITabBarControllerDelegate>

@property (strong, nonatomic) UIWindow *window;

@end

AppDelegate.m

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    // Override point for customization after application launch.


    UITabBarController *tabBarController = (UITabBarController *)self.window.rootViewController;
    tabBarController.delegate = (id)self;

    return YES;
}

- (BOOL)tabBarController:(UITabBarController *)tabBarController shouldSelectViewController:(UIViewController *)viewController {

    // here check if "viewController" is your last tab controller, then return NO and perform some actions you need
    if (viewController = self.lastTabController) {
        // do some actions
        return NO;
    }

    return YES;
}

Upvotes: 1

Related Questions