1.创建一个UIButton的分类
#import "UIButton+TJHitRect.h"
2.引入头文件
#import <objc/runtime.h>
3.给分类加属性
/** 自定义响应边界 UIEdgeInsetsMake(-3, -4, -5, -6). 表示扩大 例如: self.btn.hitEdgeInsets = UIEdgeInsetsMake(-3, -4, -5, -6); */ @property(nonatomic, assign) UIEdgeInsets hitEdgeInsets;
关联对象
static const char * kHitEdgeInsets = "hitEdgeInsets";
重写set方法
#pragma mark - set Method -(void)setHitEdgeInsets:(UIEdgeInsets)hitEdgeInsets{ NSValue *value = [NSValue value:&hitEdgeInsets withObjCType:@encode(UIEdgeInsets)]; objc_setAssociatedObject(self,kHitEdgeInsets, value, OBJC_ASSOCIATION_RETAIN_NONATOMIC); }
重写get方法
#pragma mark - get Method -(UIEdgeInsets)hitEdgeInsets{ NSValue *value = objc_getAssociatedObject(self, kHitEdgeInsets); UIEdgeInsets edgeInsets; [value getValue:&edgeInsets]; return value ? edgeInsets:UIEdgeInsetsZero; }
4.重写pointInside方法,如果button边界值无变化、不可点击、隐藏或者透明,说明没扩大按钮点击区域,继续走之前的方法。如果触摸点在UIEdgeInsets设置边缘边距后的范围内就说明点击了按钮。
#pragma mark - override super method -(BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event{ //如果 button 边界值无变化 失效 隐藏 或者透明 直接返回 if(UIEdgeInsetsEqualToEdgeInsets(self.hitEdgeInsets, UIEdgeInsetsZero) || !self.enabled || self.hidden || self.alpha == 0 ) { return [super pointInside:point withEvent:event]; }else{ CGRect relativeFrame = self.bounds; CGRect hitFrame = UIEdgeInsetsInsetRect(relativeFrame, self.hitEdgeInsets); return CGRectContainsPoint(hitFrame, point); } }
5.调用方式
self.closeBtn.hitEdgeInsets=UIEdgeInsetsMake(-10, -10, -10, -10);