UIBarButtonItem on specific views using UITabBarController
I have a UITabBarController and want a button seen only on one of the tabs, not the rest. So in my method to handle when tab bar is pressed, I add the button like this:
#pragma mark - UITabBarController delegate
- (void) tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController
{
// check for what type of class you are based on the tab pressed
...
NSMutableArray *barItems = [[self.MainToolbar items] mutableCopy];
UIBarButtonItem *sortBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"Sort" style:UIBarButtonItemStyleBordered target:self action:@selector(SortButtonPressed:)];
[barItems insertObject:sortBarButtonItem atIndex:0];
[self.MainToo开发者_Go百科lbar setItems:barItems];
Now how do I remove it when in the other views when the tabBarController is pressed without disturbing their buttons in the UIToolBar they already have that were added in IB.
This is simply achieved the same way you added the button, simply make it an ivar, which gets instanciated only once when you detect the particular view controller the first time.
// in .h
UIBarButtonItem *extraButton;
// in .m
-(void)tabBarController:(UITabBarController *)tabBarController
didSelectViewController:(UIViewController *)viewController {
// if it is the view controller you want {
NSMutableArray *barItems = [[self.MainToolbar items] mutableCopy];
if(!extraButton) {
extraButton = [[UIBarButtonItem alloc]
initWithTitle:@"Sort"
style:UIBarButtonItemStyleBordered
target:self
action:@selector(SortButtonPressed:)];
}
[barItems insertObject:sortBarButtonItem atIndex:0];
[self.MainToolbar setItems:barItems];
// else
// just remove the button
NSMutableArray *barItems = [[self.MainToolbar items] mutableCopy];
[barItems removeObjectAtIndex:0];
[self.MainToolbar setItems:barItems];
}
Don't forget to release the button later when you don't need it anymore, and it should ok.
精彩评论