Can set background image for UIBarButtonItem in nav bar, but not bottom toolbar

梦想的初衷 提交于 2019-12-08 03:23:47

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!