Search code examples
objective-ciosuikituitabbar

Programatically Create and UITabBar and detect changes


So im trying to make an application with a UITabBar not a UITabBarController so i declared the UITabBar in my headers as to make it acessable from all my methods, so to make it i just did:

tabBar = [[UITabBar alloc] initWithFrame:CGRectMake(0, 430, 320, 50)];
[self.view addSubview:tabBar];

and i used an NSMutableArray to add my objects... but in my headers i also delcaired:

@interface RootViewController: UIViewController {
IBOutlet UITabBar *tabBar;
}
@property (nonatomic, retain) UITabBar *tabBar;
- (void)tabBar:(UITabBar *)tabBar didSelectItem:(UITabBarItem *)item;

an then i made a simple function to go along with it:

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

But then when I go into the app and try to change the tab, the log returns nothing, the selected tab changes, but my log gets nothing! I've seen this function set up to do this job all over the internet, and i dont understand why it wont work for my code. So could anybody mybe tell me what im doing wrong that this function wont pick up the tab change?


Solution

  • In RootViewController.h, do this:

    @interface RootViewController : UIViewController
    
    @end
    

    In RootViewController.m, do this:

    @interface RootViewController () <UITabBarDelegate>
    @end
    
    @implementation RootViewController {
        UITabBar *tabBar;
    }
    
    #pragma mark UITabBarDelegate methods
    
    - (void)tabBar:(UITabBar *)tabBar didSelectItem:(UITabBarItem *)item {
        NSLog(@"didSelectItem: %d", item.tag);
    }
    
    #pragma mark UIViewController methods
    
    - (void)viewDidLoad {
        [super viewDidLoad];
    
        tabBar = [[UITabBar alloc] initWithFrame:CGRectMake(0, 430, 320, 50)];
        tabBar.delegate = self;
        [self.view addSubview:tabBar];
    }
    
    @end
    

    This layout takes advantage of the new LLVM compiler features of modern Objective-C.

    You don't need a property since no user of the class needs access to the tab bar. You don't need to mark anything as an IBOutlet since you aren't using Interface Builder to setup the tab bar. You don't declare the tab bar delegate method in the .h file since no client of the class will be calling that method.