UIBarButton点击区域大于customView

时间:2016-03-02 17:14:31

标签: ios objective-c uinavigationbar uibarbuttonitem uinavigationitem

我正在尝试使用导航栏中的自定义按钮,而没有左边和右边的空格边框,如下一张图片:

enter image description here

这是创建te barButton的代码:

UIImage *backImage = [UIImage imageNamed:@"back"];
UIImage *backImageTapped = [UIImage imageNamed:@"back_tap"];

UIButton *backButton = [UIButton buttonWithType:UIButtonTypeCustom];
[backButton setImage:backImage forState:UIControlStateNormal];
[backButton setImage:backImageTapped forState:UIControlStateHighlighted];

backButton.frame = CGRectMake(0, 0, 44, 44);

[backButton addTarget:self
                action:@selector(backTaped)
      forControlEvents:UIControlEventTouchUpInside];

UIBarButtonItem *backBarButton =[[UIBarButtonItem alloc] initWithCustomView:backButton];

[self.navigationItem setLeftBarButtonItem:backBarButton];

我使用UINavigationItem扩展删除空格,插入带宽负的barButtomItem:

UIBarButtonItem *space = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil];
space.width = -16;
return space;

此时它看起来很棒,但问题是两个按钮的可点击区域不是每个图像的大小,它更大,类似于下一个图像的灰色区域:

enter image description here

我已经阅读了很多问题试图通过改变hitTestEdgeInsets(https://stackoverflow.com/a/13067285/3560424)或覆盖 - (UIEdgeInsets)alignmentRectInsets的UIButton类来解决它,但似乎没有什么能解决它......

提前感谢您提供任何帮助

2 个答案:

答案 0 :(得分:3)

最后,我通过使用UIButton作为子视图的中间UIView,并使用UIView作为UIBarButtonItem的自定义视图来实现它。

问题在于我无法解释原因......但它有效

代码:

UIImage *backImage = [UIImage imageNamed:@"back"];
UIImage *backImageTapped = [UIImage imageNamed:@"back_tap"];

UIButton *backButton = [UIButton buttonWithType:UIButtonTypeCustom];
[backButton setImage:backImage forState:UIControlStateNormal];
[backButton setImage:backImageTapped forState:UIControlStateHighlighted];

backButton.frame = CGRectMake(0, 0, 44, 44);

[backButton addTarget:self
                action:@selector(backTaped)
      forControlEvents:UIControlEventTouchUpInside];

UIView *viewBackButton = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 44, 44)];
[viewBackButton addSubview:backButton];

UIBarButtonItem *backBarButton =[[UIBarButtonItem alloc] initWithCustomView:viewBackButton];

[self.navigationItem setLeftBarButtonItem:backBarButton];

答案 1 :(得分:-1)

但是如果你在故事板中添加按钮,你可以debugRelease并选择图像。像这样enter image description here