1

Is it possible to add an UIButton with UIToolbar? or we can use only UIBarButtonItem? If so how to add an UIButton in UIToolbar?

Paras Joshi
  • 20,427
  • 11
  • 57
  • 70
Saranya
  • 1,481
  • 3
  • 14
  • 26

2 Answers2

1
UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
[btn setBackgroundImage:[UIImage imageNamed:@"image.png"] forState:UIControlStateNormal];
[btn addTarget:self action:@selector(action:) forControlEvents:UIControlEventTouchUpInside];
UIBarButtonItem *barBackButton = [[UIBarButtonItem alloc] initWithCustomView:btn];
[toolBar setItems:[NSArray arrayWithObject:barBackButton]];
Amit Battan
  • 2,968
  • 2
  • 32
  • 68
0

you can add UIBarButtonItem to the UIToolBar like bellow..

This bellow is an example try this..

Just add this bellow code in viewDidLoad method and then see the UIToolBar with this two UIBarButtonItems also here i add Flixiblespace for set these two buttons with right and left corner of UIToolBar

UIBarButtonItem *flexiableItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:self action:nil];
UIBarButtonItem *item1 = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:nil];
UIBarButtonItem *item2 = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAction target:self action:nil];

UIToolbar *toolbar = [[UIToolbar alloc] init];
toolbar.frame = CGRectMake(0, 0, self.view.frame.size.width, 44);
NSArray *items = [NSArray arrayWithObjects:item1, flexiableItem, item2, nil];   
self.toolbarItems = items;

[flexiableItem release];
[items release];
[self.view addSubview:toolbar];
[toolbar release];

Check this links for more information about UIBarButtonItem and UIToolbar_Class

UPDATE:

For your this requirement you can remove that buttons and also add new button instead of old .. see the example..

NSMutableArray     *items = [[yourToolbar.items mutableCopy] autorelease];
[items removeObject: yourButtons];
yourToolbar.items = items;

i hope this help you...

Paras Joshi
  • 20,427
  • 11
  • 57
  • 70
  • At present i used barbuttonitem only. But i want hide few buttons and add new buttons in certain conditions in the same position. Since we cannot hide BarButtonItem (Only we can enable/disable). I struck. Thats why am moving for UIButton. – Saranya Jan 10 '13 at 05:23
  • @Saranya see the updated answer.. here you required to define buttons and tollbar globaly and just remove and add when you want like above .. hope now its useful to you.. :) – Paras Joshi Jan 10 '13 at 05:29
  • may be he wants the custom button only so he complete it dude.. :) – Paras Joshi Jan 10 '13 at 06:27