Tuesday, June 21, 2011

Multiple UIButtons on the UINavigationBar

I needed multiple buttons on the rightBarButtonItem in my navigation bar.

Below is the code I used, notice that I use a subclass of UIToolbar, but using the UIToolbar directly will render the same result.

I originally got the idea from HERE but it wasn't exactly what I needed, so I modified it to fit my needs.




.
.
.
.

// Comment
-(void)viewWillAppear:(BOOL)animated;
{
 [super viewWillAppear:animated];
    
    self.navigationController.navigationBar.topItem.title = @"Contact";
    
    // create a toolbar to have two buttons in the right
    UICustomToolbar* tools = [[UICustomToolbar alloc] initWithFrame:CGRectMake(0.0, 0.0, 113.0, 44.01)]; 
    
    tools.alpha = 0.5;
    
    [tools setBarStyle: UIBarStyleBlackTranslucent];
    
    [tools setTranslucent: YES];
    
    [tools setTintColor: self.navigationController.navigationBar.tintColor];
    
    // create the array to hold the buttons, which then gets added to the toolbar
    NSMutableArray* buttons = [[NSMutableArray alloc] initWithCapacity:3];

    UIBarButtonItem *callUs =  [[UIBarButtonItem alloc] initWithTitle:@"Call"
                                                                style:UIBarButtonItemStylePlain
                                                               target:self
                                                               action:@selector(dial:)];
    
    callUs.style = UIBarButtonItemStyleBordered;
    
    [buttons addObject:callUs];
    [callUs release];
    
    // create a standard "send" button
    UIBarButtonItem *send =  [[UIBarButtonItem alloc] initWithTitle:@"Send"
                                                              style:UIBarButtonItemStylePlain
                                                             target:self
                                                             action:@selector(send:)];
    
    send.style = UIBarButtonItemStyleBordered;
    
    [buttons addObject: send];
    [send release];
    
    // stick the buttons in the toolbar
    [tools setItems:buttons animated:NO];
    
    [buttons release];
    
    // and put the toolbar in the nav bar
    self.navigationController.navigationBar.topItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:tools];
    [tools release];