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

21,223

Solution 1

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.

Solution 2

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.

Solution 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

Solution 4

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.

Solution 5

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.

Share:
21,223
Doug Smith
Author by

Doug Smith

I'm a web designer playing around with iOS from England

Updated on July 16, 2020

Comments

  • Doug Smith
    Doug Smith almost 4 years

    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.)