iPhone sdk how to UIButton in UIToolbar?

2019-07-24 04:58发布

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

2条回答
神经病院院长
2楼-- · 2019-07-24 05:19

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...

查看更多
劳资没心,怎么记你
3楼-- · 2019-07-24 05:28
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]];
查看更多
登录 后发表回答