Search code examples
iphoneiosobjective-cios6

How to add bar buttons in a UIToolBar


I have created a UIToolBar and want to add three items in that like contact, date and message. I tried but i am not able to do that.Kindly help as i am new to Objective C. Here is my "ViewController.m"

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad
{
[super viewDidLoad];
UIToolbar *toolbar = [[UIToolbar alloc] init];
toolbar.frame = CGRectMake(0, 414, self.view.frame.size.width, 44);
UIBarButtonItem *contact = [[UIBarButtonItem alloc]   initWithBarButtonSystemItem:UIBarButtonSystemItemEdit target:self action:nil];
UIBarButtonItem *message = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAction target:self action:nil];

NSMutableArray *items = [[NSMutableArray alloc] initWithObjects:contact,message, nil];
[toolbar setItems:items animated:NO];
[items release];
[self.view addSubview:toolbar];
[toolbar release];
}

- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}

@end

Solution

  • In Following code i added two UIBarButton with flexSpace..
    you can add UIBarButton as you want

    UIToolbar *Toolbar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, 320, 44)];
        Toolbar.barStyle = UIBarStyleBlackTranslucent;
        [Toolbar sizeToFit];
    
         NSMutableArray *barItems = [[NSMutableArray alloc] init];
        UIBarButtonItem *flexSpace = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:self action:nil];
        [barItems addObject:flexSpace];
        [flexSpace release];
    
        UIBarButtonItem *btnCancel = [[UIBarButtonItem alloc] initWithTitle:@"Cancel" style:UIBarButtonItemStyleBordered target:self action:@selector(Cancel)];
        [barItems addObject:btnCancel];
    
        UIBarButtonItem *btnDone = [[UIBarButtonItem alloc] initWithTitle:@"Done" style:UIBarButtonItemStyleBordered target:self action:@selector(done)];
        [barItems addObject:btnDone];
    
        [Toolbar setItems:barItems animated:YES];
    

    Following Method is call when tapped on bar Button

    -(void)Cancel
    {
      // Write Code for Cancel Method
    }
    
    -(void)done
    {
      // Write Code for Done Method
    }