0

I'm using Xcode 8.0. I add a custom left barbutton to my NavBar:

UIImage * imageNormal = [UIImage imageNamed:@"InfoIcon"];
UIButton * button = [UIButton buttonWithType:UIButtonTypeCustom];
[button addTarget:self action:@selector(testPressed ) forControlEvents:UIControlEventTouchUpInside];
[button setBackgroundImage:imageNormal forState:UIControlStateNormal];

// set the frame of the button
button.frame = CGRectMake(0, 0, imageNormal.size.width, imageNormal.size.height);

UIView * view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, imageNormal.size.width, imageNormal.size.height)];
[view addSubview:button];

// set the barbuttonitem to be the view
UIBarButtonItem * barButtonItem = [[UIBarButtonItem alloc] initWithCustomView:view];

self.navigationItem.leftBarButtonItem = barButtonItem;

Here what I got:

enter image description here

unfortunately my button is not centered because the Nav bar has a custom image higher than the standard. But if I press the info Icon it works. If I change the icon position with this line of code:

button.frame = CGRectMake(0, -30, imageNormal.size.width, imageNormal.size.height);

I got the right positioning:

enter image description here

But in this case the bar button is not anymore clickable, and I don't get why this is happening.

As workaround I attach a gesture to the view:

UITapGestureRecognizer *_tapOnVideoRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self.revealViewController action:@selector(revealToggle:)];
[view addGestureRecognizer:_tapOnVideoRecognizer];

it works, but the tap is on the view and not on the button so that the changing status of the button when pressed is not working.

@JakubKnejzlik from https://stackoverflow.com/a/12554715/1320479 suggests:

This can be fixed by subclassing the wrapper view (superview of button, custom view of uibarbuttonitem) and overriding the hittest method to return button accordingly. But I have no idea how to do it

Community
  • 1
  • 1
NiBE
  • 857
  • 2
  • 16
  • 39
  • Do one thing only, initialise you bar button item with the button instead of the view. You don't need this view at all. When you change the frame of the button it's origin is no more aligned with that of the view. – Adeel Miraj Oct 02 '16 at 13:08
  • If I add the button instead of the view to the bar button, the position doesn't change! – NiBE Oct 02 '16 at 13:59

0 Answers0