Search code examples
iphoneiosuinavigationcontrolleruinavigationbaruinavigationitem

Make custom back button's clickable area smaller in Navigation controller


I've created a custom back button with the code below, however the clickable area is very big and goes well beyond the icon itself. Does anyone know how to set the clickable area, or make it the same size as the image?

Thanks

UIImage *buttonImage = [UIImage imageNamed:@"prefs"];

UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];

[button setImage:buttonImage forState:UIControlStateNormal];

button.frame = CGRectMake(0, 0, buttonImage.size.width, buttonImage.size.height);

[button addTarget:self action: @selector(handleBackButton)
    forControlEvents:UIControlEventTouchUpInside];

UIBarButtonItem *customBarItem = [[UIBarButtonItem alloc] initWithCustomView:button];

self.navigationItem.leftBarButtonItem = customBarItem;

The clickable area is shown in red.

Clickable area

Thanks!


Solution

  • If you want to prevent the click other than the button then add the custom button to UIView then set that view as custom view to the barbuttonItem

    Your code will become like this :

    UIImage *buttonImage = [UIImage imageNamed:@"prefs"];
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    [button setImage:buttonImage forState:UIControlStateNormal];
    button.frame = CGRectMake(0, 0, buttonImage.size.width, buttonImage.size.height);
    [button addTarget:self action: @selector(handleBackButton)
    forControlEvents:UIControlEventTouchUpInside];
    
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, buttonImage.size.width, buttonImage.size.height)];
    [view addSubview:button];
    
    UIBarButtonItem *customBarItem = [[UIBarButtonItem alloc] initWithCustomView:view];
    self.navigationItem.leftBarButtonItem = customBarItem;
    

    This should work as it worked for me.