196

I have a question dealing with UIButton and its hit area. I am using the Info Dark button in interface builder, but I am finding that the hit area is not large enough for some people's fingers.

Is there a way to increase the hit area of a button either programmatically or in Interface Builder without changing the size of the InfoButton graphic?

Bhavin Bhadani
  • 22,224
  • 10
  • 78
  • 108
Kevin Bomberry
  • 3,122
  • 4
  • 22
  • 18
  • If nothing is working, just add a UIButton without an image and then put an ImageView overlay ! – Varun Mar 20 '17 at 06:08
  • This would have to be the most amazingly simple question on the whole site, which has dozens of answers. I mean, I can paste the entire answer in here: `override func point(inside point: CGPoint, with event: UIEvent?) -> Bool { return bounds.insetBy(dx: -20, dy: -20).contains(point) }` – Fattie Sep 22 '19 at 20:01

36 Answers36

138

Since I am using a background image, none of these solutions worked well for me. Here is a solution that does some fun objective-c magic and offers a drop in solution with minimal code.

First, add a category to UIButton that overrides the hit test and also adds a property for expanding the hit test frame.

UIButton+Extensions.h

@interface UIButton (Extensions)

@property(nonatomic, assign) UIEdgeInsets hitTestEdgeInsets;

@end

UIButton+Extensions.m

#import "UIButton+Extensions.h"
#import <objc/runtime.h>

@implementation UIButton (Extensions)

@dynamic hitTestEdgeInsets;

static const NSString *KEY_HIT_TEST_EDGE_INSETS = @"HitTestEdgeInsets";

-(void)setHitTestEdgeInsets:(UIEdgeInsets)hitTestEdgeInsets {
    NSValue *value = [NSValue value:&hitTestEdgeInsets withObjCType:@encode(UIEdgeInsets)];
    objc_setAssociatedObject(self, &KEY_HIT_TEST_EDGE_INSETS, value, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

-(UIEdgeInsets)hitTestEdgeInsets {
    NSValue *value = objc_getAssociatedObject(self, &KEY_HIT_TEST_EDGE_INSETS);
    if(value) {
        UIEdgeInsets edgeInsets; [value getValue:&edgeInsets]; return edgeInsets;
    }else {
        return UIEdgeInsetsZero;
    }
}

- (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event {
    if(UIEdgeInsetsEqualToEdgeInsets(self.hitTestEdgeInsets, UIEdgeInsetsZero) || !self.enabled || self.hidden) {
        return [super pointInside:point withEvent:event];
    }

    CGRect relativeFrame = self.bounds;
    CGRect hitFrame = UIEdgeInsetsInsetRect(relativeFrame, self.hitTestEdgeInsets);

    return CGRectContainsPoint(hitFrame, point);
}

@end

Once this class is added, all you need to do is set the edge insets of your button. Note that I chose to add the insets so if you want to make the hit area larger, you must use negative numbers.

[button setHitTestEdgeInsets:UIEdgeInsetsMake(-10, -10, -10, -10)];

Note: Remember to import the category (#import "UIButton+Extensions.h") in your classes.

Chase
  • 11,161
  • 8
  • 42
  • 39
  • 26
    Overriding a method in a category is a bad idea. What if another category also tries to override pointInside:withEvent:? And the call to [super pointInside:withEvent] isn't calling UIButton's version of the call (if it has one)but UIButton's parent's version. – honus Jul 19 '13 at 02:41
  • @honus You are right and Apple does not recommend doing this. That being said, as long as this code is not in a shared library and just local to your application, you should be fine. – Chase Jul 19 '13 at 03:09
  • Hi Chase, is there any disadvantage of using a subclass instead? – Sid Jan 13 '14 at 16:49
  • @Sid, subclassing UIButton is tricky because the initializer is a static method. Adding methods with a category means you don't have to explicitly use your custom class which can be convenient. – Chase Jan 14 '14 at 01:30
  • 3
    You're doing too much unnecessary work, you can do two simple lines of code: `[[backButton imageView] setContentMode: UIViewContentModeCenter]; [backButton setImage:[UIImage imageNamed:@"arrow.png"] forState:UIControlStateNormal];` And just set width & height that you need:` backButton.frame = CGRectMake(5, 28, 45, 30);` – Resty Mar 28 '14 at 04:15
  • 7
    @Resty, he's using the background image, meaning that your approach won't work. – mattsson Jul 01 '14 at 08:24
  • @Chase While your claim of the code not being in a shared library is theoretically true, if Apple one day decide to implement their code in a category, there is still no guarantee which one of you wins. Using categories to override stuff is a) bad style and b) not reliable. And this is exactly what subclasses are for. Please change this to use a subclass. – uliwitness Apr 30 '16 at 15:19
  • @uliwitness I don't disagree. This sort of monkey patching is not ideal. I don't have a subclass solution unfortunately. Feel free to provide one. – Chase May 02 '16 at 09:20
  • I didn't realize how cool of a solution this was until I dove into the code more. Then, since there was this talk of subclassing, I tried my hand at a subclass implementation - http://stackoverflow.com/a/37866101/4403600. – Phillip Martin Jun 16 '16 at 18:17
78

Just set the image edge inset values in interface builder.

Samuel Goodwin
  • 1,698
  • 13
  • 17
  • 1
    I thought this wouldn't work for me because background images don't respond to the insets but I changed to setting the image property and then set a negative left edge inset for my title the width of the image and it was back on top of my image. – Dave Ross Apr 24 '13 at 02:58
  • 12
    This can also be done in code. For example, `button.imageEdgeInsets = UIEdgeInsetsMake(-10, -10, -10, -10);` – bengoesboom Oct 31 '13 at 20:30
  • Dave Ross's answer is great. For those who can't picture it, the -image bumps your title over to the right of itself (apparently), so you can click the little clicker in IB to move it back (or in code as was stated). The only negative I see is that I can't use stretchable images. Small price to pay IMO – Paul Bruneau Feb 26 '14 at 16:56
  • 7
    how to do this without stretching the image? – zonabi Jul 12 '14 at 01:39
  • Set the content mode to something like Center and not anything Scaling. – Samuel Goodwin Nov 01 '14 at 08:20
  • Update for Xcode 8.1. There is a bug in previsualization on insets when using Storyboard. http://stackoverflow.com/a/40570294/1363634 – CoderPug Nov 13 '16 at 03:37
67

Here's an elegant solution using Extensions in Swift. It gives all UIButtons a hit area of at least 44x44 points, as per Apple's Human Interface Guidelines (https://developer.apple.com/ios/human-interface-guidelines/visual-design/layout/)

Swift 2:

private let minimumHitArea = CGSizeMake(44, 44)

extension UIButton {
    public override func hitTest(point: CGPoint, withEvent event: UIEvent?) -> UIView? {
        // if the button is hidden/disabled/transparent it can't be hit
        if self.hidden || !self.userInteractionEnabled || self.alpha < 0.01 { return nil }

        // increase the hit frame to be at least as big as `minimumHitArea`
        let buttonSize = self.bounds.size
        let widthToAdd = max(minimumHitArea.width - buttonSize.width, 0)
        let heightToAdd = max(minimumHitArea.height - buttonSize.height, 0)
        let largerFrame = CGRectInset(self.bounds, -widthToAdd / 2, -heightToAdd / 2)

        // perform hit test on larger frame
        return (CGRectContainsPoint(largerFrame, point)) ? self : nil
    }
}

Swift 3:

fileprivate let minimumHitArea = CGSize(width: 100, height: 100)

extension UIButton {
    open override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
        // if the button is hidden/disabled/transparent it can't be hit
        if self.isHidden || !self.isUserInteractionEnabled || self.alpha < 0.01 { return nil }

        // increase the hit frame to be at least as big as `minimumHitArea`
        let buttonSize = self.bounds.size
        let widthToAdd = max(minimumHitArea.width - buttonSize.width, 0)
        let heightToAdd = max(minimumHitArea.height - buttonSize.height, 0)
        let largerFrame = self.bounds.insetBy(dx: -widthToAdd / 2, dy: -heightToAdd / 2)

        // perform hit test on larger frame
        return (largerFrame.contains(point)) ? self : nil
    }
}
Apollo
  • 8,874
  • 32
  • 104
  • 192
giaset
  • 956
  • 8
  • 10
51

You could also subclass UIButton or a custom UIView and override point(inside:with:) with something like:

Swift 3

override func point(inside point: CGPoint, with _: UIEvent?) -> Bool {
    let margin: CGFloat = 5
    let area = self.bounds.insetBy(dx: -margin, dy: -margin)
    return area.contains(point)
}

Objective-C

- (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event {
    CGFloat margin = 5.0;
    CGRect area = CGRectInset(self.bounds, -margin, -margin);
    return CGRectContainsPoint(area, point);
}
Jon Colverson
  • 2,986
  • 1
  • 24
  • 24
jlajlar
  • 1,118
  • 11
  • 9
  • 1
    thanks really cool solution without any additional categories. Also I simple integrate it with my buttons that I have in XIB and it works good. great answer – Matrosov Oleksandr Apr 08 '13 at 21:48
  • This is a great solution that can be extended to all other controls! I found it useful to subclass a UISearchBar for example. The pointInside method is on every UIView since iOS 2.0. BTW - Swift: func pointInside(_ point: CGPoint, withEvent event: UIEvent!) -> Bool. – Tommie C. Sep 08 '14 at 15:19
  • Thanks for this! As other said, this can be really useful with other controls! – Yanchi Feb 17 '15 at 16:14
  • This is great!! Thanks, you saved me a lot of time! :-) – Vojta Oct 28 '16 at 12:11
35

Here's Chase's UIButton+Extensions in Swift 3.0.


import UIKit

private var pTouchAreaEdgeInsets: UIEdgeInsets = .zero

extension UIButton {

    var touchAreaEdgeInsets: UIEdgeInsets {
        get {
            if let value = objc_getAssociatedObject(self, &pTouchAreaEdgeInsets) as? NSValue {
                var edgeInsets: UIEdgeInsets = .zero
                value.getValue(&edgeInsets)
                return edgeInsets
            }
            else {
                return .zero
            }
        }
        set(newValue) {
            var newValueCopy = newValue
            let objCType = NSValue(uiEdgeInsets: .zero).objCType
            let value = NSValue(&newValueCopy, withObjCType: objCType)
            objc_setAssociatedObject(self, &pTouchAreaEdgeInsets, value, .OBJC_ASSOCIATION_RETAIN)
        }
    }

    open override func point(inside point: CGPoint, with event: UIEvent?) -> Bool {
        if UIEdgeInsetsEqualToEdgeInsets(self.touchAreaEdgeInsets, .zero) || !self.isEnabled || self.isHidden {
            return super.point(inside: point, with: event)
        }

        let relativeFrame = self.bounds
        let hitFrame = UIEdgeInsetsInsetRect(relativeFrame, self.touchAreaEdgeInsets)

        return hitFrame.contains(point)
    }
}

To use it, you can:

button.touchAreaEdgeInsets = UIEdgeInsets(top: -10, left: -10, bottom: -10, right: -10)
dcRay
  • 594
  • 5
  • 9
  • 1
    Actually, we should extend `UIControl`, not `UIButton`. – Valentin Shergin Aug 10 '16 at 22:42
  • 2
    And variable `pTouchAreaEdgeInsets` must be `Int`, not `UIEdgeInsets`. (Actually, it can be any type, but `Int` is the most generic and simple type, so it is common in such construction). (Therefore I do love this approach in general. Thank you, dcRay!) – Valentin Shergin Aug 10 '16 at 22:44
  • 1
    I have try titleEdgeInsets, imageEdgeInsets, contentEdgeInset all are not working for me this extension is working well. Thank you for posting this !! Great job !! – Yogesh Patel May 13 '19 at 06:23
19

Don't set the backgroundImage property with your image, set the imageView property. Also, make sure you have imageView.contentMode set at UIViewContentModeCenter.

Maurizio
  • 4,143
  • 1
  • 29
  • 28
  • 1
    More specifically, set the button's contentMode property to UIViewContentModeCenter. Then you can make the button's frame larger than the image. Works for me! – arlomedia Sep 07 '12 at 10:49
  • FYI, UIButton does not respect UIViewContentMode: http://stackoverflow.com/a/4503920/361247 – Enrico Susatyo Apr 19 '13 at 00:47
  • @EnricoSusatyo sorry, I've clarified what APIs I was talking about. The `imageView.contentMode` can be set as `UIContentModeCenter`. – Maurizio Apr 19 '13 at 13:46
  • This works perfectly, thanks for advice! `[[backButton imageView] setContentMode: UIViewContentModeCenter]; [backButton setImage:[UIImage imageNamed:@"image.png"] forState:UIControlStateNormal];` – Resty Mar 27 '14 at 12:46
  • @Resty The above mentioned comment doesnt work for me :/ The image is resizing to the larger set frame size. – Anil May 17 '14 at 15:18
  • @Anil ok, I will try to give more details, it works when you set more **Width & Height** in **CGRectMake**, so make your button a bit larger, I recommend you to do it with custom image, here is my full working example: ` UIButton *backButton = [UIButton buttonWithType:UIButtonTypeCustom]; backButton.frame = CGRectMake(100, 100, 45, 35); [[backButton imageView] setContentMode: UIViewContentModeCenter]; [backButton setImage:[UIImage imageNamed:@"arrow.png"] forState:UIControlStateNormal]; // "arror.png" size is 19x34 [self.view addSubview:backButton]; //hit area is 45x35` – Resty May 19 '14 at 04:45
  • I tried doing the same but couldn't get it to work. Finally overrode UIButton and changed it under hitTest. Its working fine now. – Anil May 19 '14 at 05:27
19

I recommend placing a UIButton with type Custom centered over your info button. Resize the custom button to the size you want the hit area to be. From there you have two options:

  1. Check the 'Show touch on highlight' option of the custom button. The white glow will appear over the info button, but in most cases the users finger will cover this and all they will see is the glow around the outside.

  2. Set up an IBOutlet for the info button and two IBActions for the custom button one for 'Touch Down' and one for the 'Touch Up Inside'. Then in Xcode make the touchdown event set the highlighted property of the info button to YES and the touchupinside event set the highlighted property to NO.

Kyle
  • 1,620
  • 14
  • 25
14

My solution on Swift 3:

class MyButton: UIButton {

    override open func point(inside point: CGPoint, with event: UIEvent?) -> Bool {
        let relativeFrame = self.bounds
        let hitTestEdgeInsets = UIEdgeInsetsMake(-25, -25, -25, -25)
        let hitFrame = UIEdgeInsetsInsetRect(relativeFrame, hitTestEdgeInsets)
        return hitFrame.contains(point)
    }
}
Janserik
  • 2,306
  • 1
  • 24
  • 43
12

There is nothing wrong with the answers presented; however I wanted to extend jlarjlar's answer as it holds amazing potential that can add value to the same problem with other controls (e.g. SearchBar). This is because since pointInside is attached to a UIView, one is able to subclass any control to improve the touch area. This answer also shows a full sample of how to implement the complete solution.

Create a new subclass for your button (or any control)

#import <UIKit/UIKit.h>

@interface MNGButton : UIButton

@end

Next override the pointInside method in your subclass implementation

@implementation MNGButton


-(BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event
{
    //increase touch area for control in all directions by 20
    CGFloat margin = 20.0;
    CGRect area = CGRectInset(self.bounds, -margin, -margin);
    return CGRectContainsPoint(area, point);
}


@end

On your storyboard/xib file select the control in question and open the identity inspector and type in the name of your custom class.

mngbutton

In your UIViewController class for scene containing the button, change the class type for the button to the name of your subclass.

@property (weak, nonatomic) IBOutlet MNGButton *helpButton;

Link your storyboard/xib button to the property IBOutlet and your touch area will be expanded to fit the area defined in the subclass.

In addition to overriding the pointInside method together with the CGRectInset and CGRectContainsPoint methods, one should take time to examine the CGGeometry for extending the rectangular touch area of any UIView subclass. You may also find some nice tips on CGGeometry use-cases at NSHipster.

For example one could make the touch area irregular using the methods mentioned above or simply choose to make the width touch area twice as large as the horizontal touch area:

CGRect area = CGRectInset(self.bounds, -(2*margin), -margin);

NB: Substituting any UI Class control should produce similar results on extending the touch area for different controls (or any UIView subclass, like UIImageView, etc).

Community
  • 1
  • 1
Tommie C.
  • 12,895
  • 5
  • 82
  • 100
10

This works for me:

UIButton *button = [UIButton buttonWithType: UIButtonTypeCustom];
// set the image (here with a size of 32 x 32)
[button setImage: [UIImage imageNamed: @"myimage.png"] forState: UIControlStateNormal];
// just set the frame of the button (here 64 x 64)
[button setFrame: CGRectMake(xPositionOfMyButton, yPositionOfMyButton, 64, 64)];
Olof
  • 5,348
  • 4
  • 25
  • 27
  • 3
    This works, but be careful if you need to set both an image and a title to a button. In that case you will need to use setBackgoundImage which will scale your image to the new frame of the button. – Mihai Damian Aug 24 '10 at 12:52
7

I'm using a more generic approach by swizzling -[UIView pointInside:withEvent:]. This allows me to modify hit testing behavior on any UIView, not just UIButton.

Oftentimes, a button is placed inside a container view that also limits the hit testing. For instance, when a button is at the top of a container view and you want to extend the touch target upwards, you also have to extend the touch target of the container view.

@interface UIView(Additions)
@property(nonatomic) UIEdgeInsets hitTestEdgeInsets;
@end

@implementation UIView(Additions)

+ (void)load {
    Swizzle(self, @selector(pointInside:withEvent:), @selector(myPointInside:withEvent:));
}

- (BOOL)myPointInside:(CGPoint)point withEvent:(UIEvent *)event {

    if(UIEdgeInsetsEqualToEdgeInsets(self.hitTestEdgeInsets, UIEdgeInsetsZero) || self.hidden ||
       ([self isKindOfClass:UIControl.class] && !((UIControl*)self).enabled))
    {
        return [self myPointInside:point withEvent:event]; // original implementation
    }
    CGRect hitFrame = UIEdgeInsetsInsetRect(self.bounds, self.hitTestEdgeInsets);
    hitFrame.size.width = MAX(hitFrame.size.width, 0); // don't allow negative sizes
    hitFrame.size.height = MAX(hitFrame.size.height, 0);
    return CGRectContainsPoint(hitFrame, point);
}

static char hitTestEdgeInsetsKey;
- (void)setHitTestEdgeInsets:(UIEdgeInsets)hitTestEdgeInsets {
    objc_setAssociatedObject(self, &hitTestEdgeInsetsKey, [NSValue valueWithUIEdgeInsets:hitTestEdgeInsets], OBJC_ASSOCIATION_RETAIN);
}

- (UIEdgeInsets)hitTestEdgeInsets {
    return [objc_getAssociatedObject(self, &hitTestEdgeInsetsKey) UIEdgeInsetsValue];
}

void Swizzle(Class c, SEL orig, SEL new) {

    Method origMethod = class_getInstanceMethod(c, orig);
    Method newMethod = class_getInstanceMethod(c, new);

    if(class_addMethod(c, orig, method_getImplementation(newMethod), method_getTypeEncoding(newMethod)))
        class_replaceMethod(c, new, method_getImplementation(origMethod), method_getTypeEncoding(origMethod));
    else
        method_exchangeImplementations(origMethod, newMethod);
}
@end

The nice thing about this approach is you can use this even in Storyboards by adding a User Defined Runtime Attribute. Sadly, UIEdgeInsets is not directly available as a type there but since CGRect also consists of a struct with four CGFloat it works flawlessly by choosing "Rect" and filling in the values like this: {{top, left}, {bottom, right}}.

Ortwin Gentz
  • 52,648
  • 24
  • 135
  • 213
7

Don't change the behavior of UIButton.

@interface ExtendedHitButton: UIButton

+ (instancetype) extendedHitButton;

- (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event;

@end

@implementation ExtendedHitButton

+ (instancetype) extendedHitButton {
    return (ExtendedHitButton *) [ExtendedHitButton buttonWithType:UIButtonTypeCustom];
}

- (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event {
    CGRect relativeFrame = self.bounds;
    UIEdgeInsets hitTestEdgeInsets = UIEdgeInsetsMake(-44, -44, -44, -44);
    CGRect hitFrame = UIEdgeInsetsInsetRect(relativeFrame, hitTestEdgeInsets);
    return CGRectContainsPoint(hitFrame, point);
}

@end
user3109079
  • 71
  • 1
  • 1
  • If your button is 40x40, this method won't be called if the negative numbers are greater - like someone else mentioned. Otherwise this works. – James O'Brien May 13 '14 at 03:01
  • This doesn't work for me. hitFrame appears calculated properly, but pointInside: is never called when the point is outside of self.bounds. if (CGRectContainsPoint(hitFrame, point) && !CGRectContainsPoint(self.bounds, point)){ NSLog(@"Success!"); // Never called } – arsenius Oct 28 '14 at 04:26
6

I'm using the following class in Swift, to also enable an Interface Builder property to adjust the margin:

@IBDesignable
class ALExtendedButton: UIButton {

    @IBInspectable var touchMargin:CGFloat = 20.0

    override func pointInside(point: CGPoint, withEvent event: UIEvent?) -> Bool {
        var extendedArea = CGRectInset(self.bounds, -touchMargin, -touchMargin)
        return CGRectContainsPoint(extendedArea, point)
    }
}
Antoine
  • 23,526
  • 11
  • 88
  • 94
  • how to manually change this pointInside? If i've created an UIButton with old margin, but now i want to change it? – TomSawyer Oct 12 '15 at 19:49
5

I've been able to increase the hit area of the info button programmatically. The "i" graphic doesn't change scale and remains centered in the new button frame.

The size of the info button seems to be fixed to 18x19[*] in Interface Builder. By connecting it to an IBOutlet, I was able to change its frame size in code without any issues.

static void _resizeButton( UIButton *button )
{
    const CGRect oldFrame = infoButton.frame;
    const CGFloat desiredWidth = 44.f;
    const CGFloat margin = 
        ( desiredWidth - CGRectGetWidth( oldFrame ) ) / 2.f;
    infoButton.frame = CGRectInset( oldFrame, -margin, -margin );
}

[*]: Later versions of iOS appear to have increased the hit area of the info button.

otto
  • 2,230
  • 2
  • 26
  • 26
5

This is my Swift 3 Solution(based on this blogpost: http://bdunagan.com/2010/03/01/iphone-tip-larger-hit-area-for-uibutton/)

class ExtendedHitAreaButton: UIButton {

    @IBInspectable var hitAreaExtensionSize: CGSize = CGSize(width: -10, height: -10)

    override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {

        let extendedFrame: CGRect = bounds.insetBy(dx: hitAreaExtensionSize.width, dy: hitAreaExtensionSize.height)

        return extendedFrame.contains(point) ? self : nil
    }
}
arthurschiller
  • 316
  • 2
  • 9
5

Well, you can place your UIButton inside a transparent and slightly bigger UIView, and then catch the touch events on the UIView instance as in the UIButton. That way, you will still have your button, but with a bigger touch area. You will manually have to deal with selected & highlighted states con the button if the user touches the view instead of the button.

Other possibility involves using a UIImage instead of a UIButton.

Pablo Santa Cruz
  • 176,835
  • 32
  • 241
  • 292
4

Honestly. The correct code for 2023:

class ChubbyButton: UIButton {
    override func point(inside point: CGPoint, with event: UIEvent?) -> Bool {
        return bounds.insetBy(dx: -20, dy: -20).contains(point)
    }
}

Note that this works perfectly for any type of UIView:

class YourEasyToTouchView: UIView {
    override func point(inside point: CGPoint, with event: UIEvent?) -> Bool {
        return bounds.insetBy(dx: -20, dy: -20).contains(point)
    }
}

That's the whole thing.

Fattie
  • 27,874
  • 70
  • 431
  • 719
  • 1
    Nice. Excellent solution. Thanks! – Yogesh Patel Mar 10 '21 at 05:27
  • cheers @YogeshPatel . Yes, there's an unfortunate problem with iOS example code - it goes OUT OF DATE really quickly. You end up with questions on SO where the top/ticked answer is really incredibly wrong and out of date! – Fattie Mar 10 '21 at 15:56
3

Chase's custom hit test implemented as a subclass of UIButton. Written in Objective-C.

It seems to work both for init and buttonWithType: constructors. For my needs it's perfect, but since subclassing UIButton can be hairy, I'd be interested to know if anyone has a fault with it.

CustomeHitAreaButton.h

#import <UIKit/UIKit.h>

@interface CustomHitAreaButton : UIButton

- (void)setHitTestEdgeInsets:(UIEdgeInsets)hitTestEdgeInsets;

@end

CustomHitAreaButton.m

#import "CustomHitAreaButton.h"

@interface CustomHitAreaButton()

@property (nonatomic, assign) UIEdgeInsets hitTestEdgeInsets;

@end

@implementation CustomHitAreaButton

- (instancetype)initWithFrame:(CGRect)frame {
    if(self = [super initWithFrame:frame]) {
        self.hitTestEdgeInsets = UIEdgeInsetsZero;
    }
    return self;
}

-(void)setHitTestEdgeInsets:(UIEdgeInsets)hitTestEdgeInsets {
    self->_hitTestEdgeInsets = hitTestEdgeInsets;
}

- (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event {
    if(UIEdgeInsetsEqualToEdgeInsets(self.hitTestEdgeInsets, UIEdgeInsetsZero) || !self.enabled || self.hidden) {
        return [super pointInside:point withEvent:event];
    }
    CGRect relativeFrame = self.bounds;
    CGRect hitFrame = UIEdgeInsetsInsetRect(relativeFrame, self.hitTestEdgeInsets);
    return CGRectContainsPoint(hitFrame, point);
}

@end
Phillip Martin
  • 1,910
  • 15
  • 30
3

Implementation through override inherited UIButton.

Swift 2.2:

// don't forget that negative values are for outset
_button.hitOffset = UIEdgeInsets(top: -10, left: -10, bottom: -10, right: -10)
...
class UICustomButton: UIButton {
    var hitOffset = UIEdgeInsets()

    override func pointInside(point: CGPoint, withEvent event: UIEvent?) -> Bool {
        guard hitOffset != UIEdgeInsetsZero && enabled && !hidden else {
            return super.pointInside(point, withEvent: event)
        }
        return UIEdgeInsetsInsetRect(bounds, hitOffset).contains(point)
    }
}
dimpiax
  • 12,093
  • 5
  • 62
  • 45
3

Base on giaset's answer above (which I found the most elegant solution), here is the swift 3 version:

import UIKit

fileprivate let minimumHitArea = CGSize(width: 44, height: 44)

extension UIButton {
    open override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
        // if the button is hidden/disabled/transparent it can't be hit
        if isHidden || !isUserInteractionEnabled || alpha < 0.01 { return nil }

        // increase the hit frame to be at least as big as `minimumHitArea`
        let buttonSize = bounds.size
        let widthToAdd = max(minimumHitArea.width - buttonSize.width, 0)
        let heightToAdd = max(minimumHitArea.height - buttonSize.height, 0)
        let largerFrame = bounds.insetBy(dx: -widthToAdd / 2, dy: -heightToAdd / 2)

        // perform hit test on larger frame
        return (largerFrame.contains(point)) ? self : nil
    }
}
Thanh-Nhon Nguyen
  • 3,402
  • 3
  • 28
  • 41
2

WJBackgroundInsetButton.h

#import <UIKit/UIKit.h>

@interface WJBackgroundInsetButton : UIButton {
    UIEdgeInsets backgroundEdgeInsets_;
}

@property (nonatomic) UIEdgeInsets backgroundEdgeInsets;

@end

WJBackgroundInsetButton.m

#import "WJBackgroundInsetButton.h"

@implementation WJBackgroundInsetButton

@synthesize backgroundEdgeInsets = backgroundEdgeInsets_;

-(CGRect) backgroundRectForBounds:(CGRect)bounds {
    CGRect sup = [super backgroundRectForBounds:bounds];
    UIEdgeInsets insets = self.backgroundEdgeInsets;
    CGRect r = UIEdgeInsetsInsetRect(sup, insets);
    return r;
}

@end
William Jockusch
  • 26,513
  • 49
  • 182
  • 323
2

Never override method in category. Subclass button and override - pointInside:withEvent:. For example if your button's side is smaller than 44 px (which is recommended as minimum tappable area) use this:

- (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event
{
    return (ABS(point.x - CGRectGetMidX(self.bounds)) <= MAX(CGRectGetMidX(self.bounds), 22)) && (ABS(point.y - CGRectGetMidY(self.bounds)) <= MAX(CGRectGetMidY(self.bounds), 22));
}
user500
  • 4,519
  • 6
  • 43
  • 56
2

I made a library for this very purpose.

You can choose to use a UIView category, no subclassing required:

@interface UIView (KGHitTesting)
- (void)setMinimumHitTestWidth:(CGFloat)width height:(CGFloat)height;
@end

Or you can subclass your UIView or UIButton and set the minimumHitTestWidth and/or minimumHitTestHeight. Your button hit-test area will then be represented by these 2 values.

Just like other solutions, it uses the - (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event method. The method is called when iOS performs hit-testing. This blog post has a good description on how iOS hit-testing works.

https://github.com/kgaidis/KGHitTestingViews

@interface KGHitTestingButton : UIButton <KGHitTesting>

@property (nonatomic) CGFloat minimumHitTestHeight; 
@property (nonatomic) CGFloat minimumHitTestWidth;

@end

You can also just subclass and use the Interface Builder without writing any code: enter image description here

kgaidis
  • 14,259
  • 4
  • 79
  • 93
  • 1
    I ended up installing this just for the sake of speed. Adding IBInspectable was a great idea thanks for putting this together. – user3344977 Jan 18 '16 at 03:06
1

I'm use this trick for button inside tableviewcell.accessoryView to enlarge its touch area

#pragma mark - Touches

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *touch                  = [touches anyObject];
    CGPoint location                = [touch locationInView:self];
    CGRect  accessoryViewTouchRect  = CGRectInset(self.accessoryView.frame, -15, -15);

    if(!CGRectContainsPoint(accessoryViewTouchRect, location))
        [super touchesBegan:touches withEvent:event];
}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *touch                  = [touches anyObject];
    CGPoint location                = [touch locationInView:self];
    CGRect  accessoryViewTouchRect  = CGRectInset(self.accessoryView.frame, -15, -15);

    if(CGRectContainsPoint(accessoryViewTouchRect, location) && [self.accessoryView isKindOfClass:[UIButton class]])
    {
        [(UIButton *)self.accessoryView sendActionsForControlEvents:UIControlEventTouchUpInside];
    }
    else
        [super touchesEnded:touches withEvent:event];
}
abuharsky
  • 1,151
  • 12
  • 21
1

I just did the port of the @Chase solution in swift 2.2

import Foundation
import ObjectiveC

private var hitTestEdgeInsetsKey: UIEdgeInsets = UIEdgeInsetsZero

extension UIButton {
    var hitTestEdgeInsets:UIEdgeInsets {
        get {
            let inset = objc_getAssociatedObject(self, &hitTestEdgeInsetsKey) as? NSValue ?? NSValue(UIEdgeInsets: UIEdgeInsetsZero)
            return inset.UIEdgeInsetsValue()
        }
        set {
            let inset = NSValue(UIEdgeInsets: newValue)
            objc_setAssociatedObject(self, &hitTestEdgeInsetsKey, inset, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
        }
    }

    public override func pointInside(point: CGPoint, withEvent event: UIEvent?) -> Bool {
        guard !UIEdgeInsetsEqualToEdgeInsets(hitTestEdgeInsets, UIEdgeInsetsZero) && self.enabled == true && self.hidden == false else {
            return super.pointInside(point, withEvent: event)
        }
        let relativeFrame = self.bounds
        let hitFrame = UIEdgeInsetsInsetRect(relativeFrame, hitTestEdgeInsets)
        return CGRectContainsPoint(hitFrame, point)
    }
}

an you can use like this

button.hitTestEdgeInsets = UIEdgeInsetsMake(-10, -10, -10, -10)

For any other reference see https://stackoverflow.com/a/13067285/1728552

Community
  • 1
  • 1
Serluca
  • 2,102
  • 2
  • 19
  • 31
1

I'm seeing a lot of solutions that either don't quite hit the mark or require specifying some fixed insets to add. Here's a solution for a simple UIView subclass that will extend the hit rect of the view to at least 44 x 44; if either of the dimensions is already greater than that, then it doesn't artificially pad that dimension.

This ensures that a button will always have the recommended minimum touch size of 44 x 44 without needing any manual configuration, calculation, or image padding:

override func point(inside point: CGPoint, with event: UIEvent?) -> Bool {
    let minimumTouchSize: CGFloat = 44.0
    let center: CGPoint = .init(x: self.bounds.midX, y: self.bounds.midY)

    let minimumHitRect: CGRect =
        .init(center: center, size: .zero)
        .insetBy(
            dx: -minimumTouchSize / 2.0,
            dy: -minimumTouchSize / 2.0
        )

    let fullHitRect = self.bounds.union(minimumHitRect)

    return fullHitRect.contains(point)
}
CIFilter
  • 8,647
  • 4
  • 46
  • 66
  • Short of Apple building in a better solution, this seems to be the most generic and foolproof answer with least amount of side effects. I think forcing opt-in via subclass is much safer. My only complaint for most of these workarounds is it's non-obvious to junior devs and potentially a source of debugging confusion, but I don't have any better, simple solutions to offer! – MechEthan Apr 08 '21 at 16:49
0

I have followed Chase's response and it works great, one single problem when you create the arrea too big, bigger than the zone where the button gets deselected (if the zone wasn't bigger) it doesn't call the selector for the UIControlEventTouchUpInside event.

I think the size is over 200 any any direction or something like that.

Unreal Dragon
  • 191
  • 1
  • 8
0

I am so late to this game, but wanted to weigh in on a simple technique that might solve your problems. Here is a typical programmatic UIButton snippet for me:

UIImage *arrowImage = [UIImage imageNamed:@"leftarrow"];
arrowButton = [[UIButton alloc] initWithFrame:CGRectMake(15.0, self.frame.size.height-35.0, arrowImage.size.width/2, arrowImage.size.height/2)];
[arrowButton setBackgroundImage:arrowImage forState:UIControlStateNormal];
[arrowButton addTarget:self action:@selector(onTouchUp:) forControlEvents:UIControlEventTouchUpOutside];
[arrowButton addTarget:self action:@selector(onTouchDown:) forControlEvents:UIControlEventTouchDown];
[arrowButton addTarget:self action:@selector(onTap:) forControlEvents:UIControlEventTouchUpInside];
[arrowButton addTarget:self action:@selector(onTouchUp:) forControlEvents:UIControlEventTouchDragExit];
[arrowButton setUserInteractionEnabled:TRUE];
[arrowButton setAdjustsImageWhenHighlighted:NO];
[arrowButton setTag:1];
[self addSubview:arrowButton];

I'm loading a transparent png Image for my button and setting the background image. I'm setting the frame based on the UIImage and scaling by 50% for retina. OK, maybe you agree with the above or not, BUT if you want to make the hit area BIGGER and save yourself a headache:

What I do, open the image in photoshop and simply increase the canvas size to 120% and save. Effectively you've just made the image bigger with transparent pixels.

Just one approach.

chrisallick
  • 1,330
  • 17
  • 18
0

@jlajlar 's answer above seemed good and straightforward but does not match Xamarin.iOS, so I converted it into Xamarin. If you looking for a solution on a Xamarin iOS, there here it goes:

public override bool PointInside (CoreGraphics.CGPoint point, UIEvent uievent)
{
    var margin = -10f;
    var area = this.Bounds;
    var expandedArea = area.Inset(margin, margin);
    return expandedArea.Contains(point);
}

You can add this method to the class where you are overriding UIView or UIImageView. This worked nicely :)

Has AlTaiar
  • 4,052
  • 2
  • 36
  • 37
0

None of the answers works perfect for me, because I use background image and a title on that button. Moreover, the button will resize as screen size changes.

Instead, I enlarge the tap area by making the png transparent area larger.

Jakehao
  • 1,019
  • 8
  • 15
0

This Swift version lets you define a minimum hit size for all UIButtons. Crucially, it also handles the case when UIButtons are hidden, which many answers neglect.

extension UIButton {
    public override func hitTest(point: CGPoint, withEvent event: UIEvent?) -> UIView? {
        // Ignore if button hidden
        if self.hidden {
            return nil
        }

        // If here, button visible so expand hit area
        let hitSize = CGFloat(56.0)
        let buttonSize = self.frame.size
        let widthToAdd = (hitSize - buttonSize.width > 0) ? hitSize - buttonSize.width : 0
        let heightToAdd = (hitSize - buttonSize.height > 0) ? hitSize - buttonSize.height : 0
        let largerFrame = CGRect(x: 0-(widthToAdd/2), y: 0-(heightToAdd/2), width: buttonSize.width+widthToAdd, height: buttonSize.height+heightToAdd)
        return (CGRectContainsPoint(largerFrame, point)) ? self : nil
    }
}
Crashalot
  • 33,605
  • 61
  • 269
  • 439
0

Similar to Zhanserik's, with variable extension and updated for Swift 4.2:

class ButtonWithExtendedHitArea: UIButton {

    var extention: CGFloat

    required init(extendBy: CGFloat) {
        extention = extendBy

        super.init(frame: .zero)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override open func point(inside point: CGPoint, with event: UIEvent?) -> Bool {
        let relativeFrame = self.bounds
        let hitTestEdgeInsets = UIEdgeInsets(top: -extention, left: -extention, bottom: -extention, right: -extention)
        let hitFrame = relativeFrame.inset(by: hitTestEdgeInsets)
        return hitFrame.contains(point)
    }

}
MT1asli8ghwoi
  • 221
  • 2
  • 11
0

@antoine's answer formatted for Swift 4

final class ExtendedHitButton: UIButton {
    
    override func point( inside point: CGPoint, with event: UIEvent? ) -> Bool {
        let relativeFrame = self.bounds
        let hitTestEdgeInsets = UIEdgeInsets(top: -44, left: -44, bottom: -44, right: -44) // Apple recommended hit target
        let hitFrame = relativeFrame.inset(by: hitTestEdgeInsets)
        return hitFrame.contains( point );
    }
}
DZoki019
  • 382
  • 2
  • 13
spfursich
  • 5,045
  • 3
  • 21
  • 24
-1

Swift:

override func viewWillAppear(animated: Bool) {
        self.sampleButton.frame = CGRectInset(self.sampleButton.frame, -10, -10);
    }
Alvin George
  • 14,148
  • 92
  • 64
-2
override func point(inside point: CGPoint, with event: UIEvent?) -> Bool {
    let inset = UIEdgeInsets(top: -adjustHitY * 0.5, left: -adjustHitX * 0.5, bottom: -adjustHitY * 0.5, right: -adjustHitX * 0.5)
    return UIEdgeInsetsInsetRect(bounds, inset).contains(point)
}
Azon
  • 57
  • 4
-2
  • Without overriding in categories or extensions
  • 44x44 minimum per guidelines

My take:

open class MinimumTouchAreaButton: UIButton {
    open override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
        guard !self.isHidden, self.isUserInteractionEnabled, self.alpha > 0 else { return nil }
        let expandedBounds = bounds.insetBy(dx: min(bounds.width - 44, 0), dy: min(bounds.height - 44, 0))
        return expandedBounds.contains(point) ? self : nil
    }
} 
Jacob Jennings
  • 2,796
  • 1
  • 24
  • 26