Friday, 31 July 2015

Increase button hit area by changing the Edge Inset. UIButton with UIEdgeInsetsMake.

#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



Usage-

 _backBtn = [[UIButton alloc]initWithFrame:CGRectMake(16, 12, 28, 28)];    
    [_backBtn setBackgroundImage:[UIImage imageNamed:@"backphoto"] forState:UIControlStateNormal];
    [_backBtn addTarget:self action:@selector(backButtonClicked) forControlEvents:UIControlEventTouchUpInside];
    [_backBtn setHitTestEdgeInsets:UIEdgeInsetsMake(-15, -15, -15, -15)];//increase the hit area of button by 15 on all sides top,left,bottom,right


1 comment:

  1. Hi!
    Thanks for your post :)

    I found this post was very helpful for me so I'd like to use this code for my app. (commercial)
    Can you let me know which license is used for your post?

    ReplyDelete