cmacera
cmacera

Reputation: 1130

UIBarButton tap area bigger than customView

i am trying to use custom buttons in my navigation bar without left&right spaces to border, like next image:

enter image description here

This is the code to create 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];

And I remove the spaces using a UINavigationItem extension that insert a barButtomItem with negative width:

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

At this point it looks great, but the problem is that the tappable area for both buttons are not the size of each image, it is bigger, something like the gray areas of next image:

enter image description here

I have read lot of questions trying to solve it with a UIButton category that change the hitTestEdgeInsets (https://stackoverflow.com/a/13067285/3560424) or overriding the - (UIEdgeInsets)alignmentRectInsets, but nothing seems to solve it for me...

Thanks in advance for any help

Upvotes: 2

Views: 1603

Answers (1)

cmacera
cmacera

Reputation: 1130

Finally I have achieved it by using an intermediate UIView with the UIButton as subview, and using the UIView as custom view for the UIBarButtonItem.

The problem is that I can not explain why... but it works

the code:

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];

Upvotes: 4

Related Questions