2

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!

Sandy
  • 2,572
  • 7
  • 40
  • 61
  • Could try logging buttonImage.size.width/height and see if it's what it is supposed to be, and if it's the problem hard code the W/H – Sam May 15 '13 at 04:04
  • Take a look http://stackoverflow.com/a/11716377/1328096 – jamil May 15 '13 at 04:14

2 Answers2

6

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.

Prasad Devadiga
  • 2,573
  • 20
  • 43
0

@Prasad Devediga, swift version works greatly:

        let btnName = UIButton()
        btnName.setImage(UIImage(named: "settings_filled_25"), forState: .Normal)
        btnName.frame = CGRectMake(0, 0, 30, 30)
        btnName.addTarget(self, action: Selector("toggleRight"), forControlEvents: .TouchUpInside)

        var rightView = UIView()
        rightView.frame = CGRectMake(0, 0, 30, 30)
        rightView.addSubview(btnName)

        let rightBarButton = UIBarButtonItem()
        rightBarButton.customView = rightView
        self.navigationItem.rightBarButtonItem = rightBarButton
haydark
  • 1
  • 1
  • 2