How to increase tapable (hitting) area of (custom Type) UIButton without increasing size of background image

Make the UIButton of type buttonWithType:UIButtonTypeCustom and assign to it an image of a smaller size.

Do not set the image as the background image or it'll grow with the button. Set it as the main image instead.

For example if you want to set the tappable area to a 64x64 size and you want to show an image sized 32x32: the button size should be be 64x64 and the image size should be 32x32.

Programmatically:

 UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];

// use an image with the desired size (for example 32x32)
[button setImage: [UIImage imageNamed: @"buttonIcon.png"] forState: UIControlStateNormal];
// just set the frame of the button (64x64)
[button setFrame: CGRectMake(xPositionOfMyButton, yPositionOfMyButton, 64, 64)];

Interface Builder:

Interface Builder example


Subclass the superview of the UIButton, and override hitTest:withEvent:

- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event
{
    CGPoint buttonPoint = [self convertPoint:point toView:_button];
    if ([_button pointInside:buttonPoint withEvent:event]) { // you may add your requirement here
        return _button;
    }
    return [super hitTest:point withEvent:event];
}

Use the design approach you like (Interface Builder / Visual Format Language) together with Autolayout and layout the UIButton with the required size. Set title or image as content and use a transparent image with the size of the tapable area as background image.

_button = [UIButton buttonWithType:UIButtonTypeCustom];
[_button setImage:[UIImage imageNamed:@"contentImage"] forState:UIControlStateNormal];
[_button setBackgroundImage:[UIImage imageNamed:@"transparentImage"] forState:UIControlStateNormal];

Here a example with _button.layer.borderWidth = 1.

Example

Tags:

Ios

Uibutton

Ios5