问题
So this works when adding the item to the nav bar, but when i add it to the toolbar set in the bottom bar via interface builder, the background image doesn't show up.
UIBarButtonItem *resetButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"Reset" style:UIBarButtonItemStylePlain target:self action:@selector(resetCriteria:)];
UIImage *img = [UIImage imageNamed:@"someImage.png"];
img = [img stretchableImageWithLeftCapWidth:5 topCapHeight:20];
[resetButtonItem setBackgroundImage:img forState:UIControlStateNormal barMetrics:UIBarMetricsDefault];
self.toolbarItems = [NSArray arrayWithObjects: resetButtonItem, nil];
Not only does the background not appear, none of the other behaviors work as well (but they work fine when adding these barbutton items to the nav bar)
回答1:
You should try the following method to do the same.
Setting custom view in UIBarButtonItem.
UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
btn.frame = CGRectMake(0, 0, 30, 30);
[btn setImage:[UIImage imageNamed:@"someImage.png"] forState:UIControlStateNormal];
[btn addTarget:self action:@selector(resetCriteria:) forControlEvents:UIControlEventTouchUpInside];
UIBarButtonItem *Item = [[UIBarButtonItem alloc] initWithCustomView:btn];
self.toolbarItems = [NSArray arrayWithObject:Item];
[Item release];
We can set any view in UIBarButtonItem with CustomView init method. We could set the ImageView. But ImageView doesnot handle UIControl Events.
来源:https://stackoverflow.com/questions/11943638/can-set-background-image-for-uibarbuttonitem-in-nav-bar-but-not-bottom-toolbar