更改UINavigationBar中UIBarButtonItem的宽度 [英] Change width of a UIBarButtonItem in a UINavigationBar
问题描述
我正在创建一个UIBarButtonItem并将其添加到我的导航栏中,如下所示:
I am creating a UIBarButtonItem and adding it to my navigation bar like so:
(void)viewDidLoad {
...
// Add the refresh button to the navigation bar
UIButton *refreshButton = [UIButton buttonWithType:UIButtonTypeCustom];
[refreshButton setFrame:CGRectMake(0,0,30,30)];
[refreshButton setImage:[UIImage imageNamed:@"G_refresh_icon.png"] forState:UIControlStateNormal];
[refreshButton addTarget:self action:@selector(refreshData) forControlEvents:UIControlEventTouchUpInside];
UIBarButtonItem *refreshBarButton = [[[UIBarButtonItem alloc] initWithCustomView:refreshButton] autorelease];
self.navigationItem.leftBarButtonItem = refreshBarButton;
}
我跑步时看起来是正确的,但我可以选择按钮项目点击导航栏从x = 0到大约100.我如何调整可选区域的宽度为30 px?
It looks correct when I run, but I can select the bar button item by tapping the navigation bar anywhere from x = 0 to roughly 100. How can I adjust the selectable area to have a width of 30 px?
推荐答案
您可以考虑的一种方法是通过调用 initWithCustomView:
来创建 UIBarButtonItem
。这并不理想,因为您没有开箱即用的选定状态,并且您必须使用按钮图像合成带边框的背景(如果想要的话),但是使用它可以更直接地为您指定框架工具栏项目。如果您使用文字作为标题而不是图像,则可能仍需要将背景图像添加为子视图。无论如何,我现在遇到同样的问题,这段代码适用于我:
One approach you might consider is creating a UIBarButtonItem
by calling initWithCustomView:
. This is not ideal in that you don't get "selected" states out of the box AND you have to composite your bordered background (if want that look) with your button image, but with that you can more directly specify a frame for your toolbar item. If you're using text for your title instead of images you may still need add in a background image as a subview. Anyway, I'm having the same problem right now and this code works for me:
UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"button-image.png"]];
imageView.frame = CGRectMake(0, 0, 43, 30);
UIBarButtonItem *barButtonItem = [[UIBarButtonItem alloc] initWithCustomView:imageView];
self.navigationItem.leftBarButtonItem = barButtonItem;
现在这是我知道限制<$ c $自动调整大小的唯一方法c> UIBarButtonItem 添加到 UINavigationController
的 navigationItem
。
Right now this is the only way I know of restricting the auto-sizing of the UIBarButtonItem
s added to the UINavigationController
's navigationItem
.
这篇关于更改UINavigationBar中UIBarButtonItem的宽度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!