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

两盒软妹~` 提交于 2019-11-28 23:25:27
Prasad Devadiga

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.

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.

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

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.

korat prashant

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;

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.

Alexander Merchi

Change button frame to large and change your line

[backButton setBackgroundImage:backButtonImage forState:UIControlStateNormal];

to:

[backButton setImage:backButtonImage forState:UIControlStateNormal];

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];

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

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!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!