Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

iOS Toolbar

Use of Toolbars

We can use a toolbar to modify view elements.

For example, the inbox bar in the Mail application has Delete, Share, Reply, and so on. As shown below:

toolbar

Important Properties

Add the custom method addToolbar

-(void)addToolbar

{

    UIBarButtonItem *spaceItem = [[UIBarButtonItem alloc] 

    initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace

    target:nil action:nil];

    UIBarButtonItem *customItem1 = [[UIBarButtonItem alloc]

    initWithTitle:@"Tool1" style:UIBarButtonItemStyleBordered 

    target:self action:@selector(toolBarItem1:)];

    UIBarButtonItem *customItem2 = [[UIBarButtonItem alloc]

    initWithTitle:@"Tool2" style:UIBarButtonItemStyleDone 

    target:self action:@selector(toolBarItem2:)];

    NSArray *toolbarItems = [NSArray arrayWithObjects: 

    customItem1,spaceItem, customItem2, nil];

    UIToolbar *toolbar = [[UIToolbar alloc]initWithFrame:

    CGRectMake(0, 366+54, 320, 50)];

    [toolbar setBarStyle:UIBarStyleBlackOpaque];

    [self.view addSubview:toolbar];

    [toolbar setItems:toolbarItems];

}

To understand the actions performed, we add a UILabel IBOutlet in our ViewController.xib and create an IBOutlet for UILabel named label.

We also need to add two methods to perform the actions of the toolbar items as follows:

-(IBAction)toolBarItem1:(id)sender{

    [label setText:@"Tool 1 Selected"];

}



-(IBAction)toolBarItem2:(id)sender{

    [label setText:@"Tool 2 Selected"];    

}

Update viewDidLoad in ViewController.m as follows:

- (void)viewDidLoad

{

    [super viewDidLoad];

    // The method hideStatusbar called after 2 seconds

    [self addToolbar];    

    // Do any additional setup after loading the view, typically from a nib.

}

Output

Now when we run the application we will see the following output.

toolbarOutput

Click the tool1 and tool2 bar buttons we get

toolbarActionOutput