Custom UIBarButtonItems from UIButtons with custom images - is it possible to make the tap targets larger?
Asked Answered
B

10

16

I'm making UIBarButtons as follows:

// Create "back" UIBarButtonItem
UIButton *backButton = [UIButton buttonWithType:UIButtonTypeCustom];
backButton.frame = CGRectMake(0, 0, 28, 17);
[backButton addTarget:self action:@selector(backButtonTapped) forControlEvents:UIControlEventTouchUpInside];
backButton.showsTouchWhenHighlighted = YES;

UIImage *backButtonImage = [UIImage imageNamed:@"back-button.png"];
[backButton setBackgroundImage:backButtonImage forState:UIControlStateNormal];

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

[toolBarItems addObject:backBarButtonItem];

However, the tap targets are tiny. More precisely, they're the size of the custom images. (Which again, are tiny.) Is there any way to increase the size of their tap target?

(Note: altering the frame property of the UIButtons just stretches the image.)

Barclay answered 8/5, 2013 at 23:2 Comment(1)
can you provide the images so we can replicate/see the exact issue?Lambda
S
26

Small changes to your code will do the stuff

Changes needed :

  • I am assuming that the size of backButtonImage is {28,17} and setting the button frame as CGRectMake(0, 0, 48, 37) `
  • remove the backGroundImage and use setImage:
  • set the property imageEdgeInsets to UIEdgeInsetsMake(10, 10, 10, 10)

Your code will become like this:

UIButton *backButton = [UIButton buttonWithType:UIButtonTypeCustom];
backButton.frame = CGRectMake(0, 0, 48, 37);
[backButton addTarget:self action:@selector(backButtonTapped) forControlEvents:UIControlEventTouchUpInside];
backButton.showsTouchWhenHighlighted = YES;

UIImage *backButtonImage = [UIImage imageNamed:@"back-button.png"];
[backButton setImage:backButtonImage forState:UIControlStateNormal];

backButton.imageEdgeInsets = UIEdgeInsetsMake(10, 10, 10, 10);

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

[toolBarItems addObject:backBarButtonItem];

You can change the value for the frame and the imageEdgeInsets as per your requirements.
This code worked for me.

Spelaean answered 17/5, 2013 at 7:17 Comment(0)
U
5

You can change the UIBarButtonItem's width property

backBarButtonItem.width = x;

Unfortunately you can't change the height is way, because there is no height property.

What you can do however is pass UIBarButtonItem an UIButton with a defined frame using initWithCustomView

for example:

    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];

    UIImage *backButtonImage = [UIImage imageNamed:@"back-button.png"];

   [button setBackgroundImage:backButtonImage forState:UIControlStateNormal];

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

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

If your image looks stretched, make sure you maintain the same aspect ratio! Or make sure the image is exactly the same size.

Unmanly answered 8/5, 2013 at 23:8 Comment(2)
I need the height as well.Barclay
@DougSmith I have updated my answer for you. Hope it is more helpful now.Unmanly
E
3

1) Add a category to your UIButton
2) Add new properties to the category
3) Add your method to initialise the back button
4) Override -(BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event
5) Subclass toolBarItems

@implementation UIButton (yourButtonCategory)
@dynamic shouldHitTest; // boolean
@dynamic hitTestRect; // enlarge rect of the button
@dynamic buttonPressedInterval; // interval of press, sometimes its being called twice

-(id)initBackBtnAtPoint:(CGPoint)_point{
// we only need the origin of the button since the size and width are fixed so the image won't be stretched
    self = [self initWithFrame:CGRectMake(_point.x, _point.y, 28, 17)];   
    [self setBackgroundImage:[UIImage imageNamed:@"back-button.png"]forState:UIControlStateNormal];

    self.shouldHitTest = CGRectMake(self.frame.origin.x - 25, self.frame.origin.y-10, self.frame.size.width+25, self.frame.size.height+25); // this will be the enlarge frame of the button
    self.shouldHitTest = YES;
    return self;
}


-(BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event{
BOOL shouldReturn = [super pointInside:point withEvent:event];
NSSet *touches = [event allTouches];
BOOL shouldSendTouches = NO;

for (UITouch *touch in touches) {
    switch (touch.phase) {
        case UITouchPhaseBegan:
            shouldSendTouches = YES;
            break;
        default:
            shouldSendTouches = NO;
            break;
    }
}


if(self.shouldHitTest){

    double elapse = CFAbsoluteTimeGetCurrent();
    CGFloat totalElapse = elapse - self.buttonPressedInterval;
    if (totalElapse < .32) {
        return NO;
        // not the event we were interested in
    } else {
                    // use this call

        if(CGRectContainsPoint(self.hitTestRect, point)){
            if(shouldSendTouches){
                self.buttonPressedInterval = CFAbsoluteTimeGetCurrent();

                [self sendActionsForControlEvents:UIControlEventTouchUpInside];
            }

            return NO;
        }
    }

}

return shouldReturn;

}


-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{

[super touchesBegan:touches withEvent:event];
UITouch *touch = [touches anyObject]; 
CGPoint touch_point = [touch locationInView:self];
[self pointInside:touch_point withEvent:event];
}

@end

Lets say the touch event doesn't trigger we need the view its in to call the button so in toolBarItems we do something like:

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    [super touchesBegan:touches withEvent:event];
    for(id subs in self.subviews){
        if([subs isKindOfClass:[UIButton class]]){
            [subs touchesBegan:touches withEvent:event];
        }
    }


}

then thats it. we enlarge the frame without enlarging the actual button.

you just initial your button like: UIButton *btn = [[UIButton alloc]initBackBtnAtPoint:CGPointMake(0,0)];

Hope it helps

Epigone answered 16/5, 2013 at 5:41 Comment(0)
D
1

When you call initWithCustomView, the UIBarButtonItem delegates event handling to the custom view, which, in your case, is the UIButton. In turn, the UIButton is getting its bounds from the image, and as a background image, it is expected to stretch to fill new bounds as needed.

Instead, set the image and imageInsets properties directly on the UIBarButtonItem. These properties are declared on the parent class, UIBarItem. You may also wish to set their landscape variants.

Dacoity answered 11/5, 2013 at 5:40 Comment(0)
C
1

mmm... for what you need to achieve - that is no image stretch - there's a simple way:

1) use Gimp or photoshop and create a transparent layer below your image, so that it matches the size you want.

2) merge down and create retina and non-retina images.

3) update your code so that it reflect the new image size.

4) assign the images and then run your code.

This way your original image won't be stretched because it's boundaries will take into account the transparent portion of it.

Other than that, you can probably do this all programatically, but I doubt this is a good idea, unless you planned to dive into UIGraphics for other reasons.

Contingent answered 11/5, 2013 at 14:6 Comment(0)
A
1

Change button frame to large and change your line

[backButton setBackgroundImage:backButtonImage forState:UIControlStateNormal];

to:

[backButton setImage:backButtonImage forState:UIControlStateNormal];
Anamorphoscope answered 16/5, 2013 at 10:47 Comment(0)
O
1

You need to change three line of code and hope its working.

1)Change the backButton width as per your need.

2)Set backButton's Image instead of backButton's BackgroundImage

[backButton setImage:backButtonImage forState:UIControlStateNormal];

3)Also set backButton's contentHorizontalAlignment

backButton.contentHorizontalAlignment=UIControlContentHorizontalAlignmentLeft;
Ollieollis answered 17/5, 2013 at 6:30 Comment(0)
F
1

Just use

[button setImage:backButtonImage forState:UIControlStateNormal];

instead of

[backButton setBackgroundImage:backButtonImage forState:UIControlStateNormal];

and set the frame to whatever you like. The image will then be centered and the button will receive the touch in the given frame.

Something like this:

UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
button.frame = CGRectMake(50, 50, 50, 50);
[button setImage:backButtonImage forState:UIControlStateNormal];
Fitful answered 17/5, 2013 at 14:17 Comment(2)
This doesn't work for me. The image always stretches to fill the entire button.Biosphere
@Biosphere because you need to set correct contentMode for the button of course. Default value is probably UIViewContentModeScaleToFill, set it to what you need (maybe UIViewContentModeCenter)Fitful
U
0

you should be able to just set the edge insets on the button.

so set the frame of the button to be larger than the image, then set the edge insets on the button.

so to expand your width by by 10 pixels on each side something like this should work

backButton.frame = CGRectMake(0,0,28,37);
backButton.imageEdgeInsets = UIEdgeInsetsMake(0, 10, 0, 10);
Unintentional answered 8/5, 2013 at 23:8 Comment(1)
That still stretches the image.Barclay
L
0

Increase the UIButton frames(up to the tap size you want)

      button.frame = CGRectMake(0, 0, 56, 20);

If you want to see the image for complete button please write following method

      [backButton setBackgroundImage:backButtonImage forState:UIControlStateNormal];

If you want to see the image actual size (Dont worry tap size is your button size only)

      [backButton setImage:backButtonImage forState:UIControlStateNormal];

And finally

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

Hope it helps you!

Lesbos answered 16/5, 2013 at 14:6 Comment(2)
What do you mean by "complete button"?Barclay
Means, if you give button size is bigger than image actual size, image will be stretch and show it for complete button.Lesbos

© 2022 - 2024 — McMap. All rights reserved.