我们可以为UIButton建立一个Category,然后利用runtime的绑定属性,来扩大响应区域。
先看一下.h文件里的,只声明了一个函数。使用的时候直接利用这个函数扩大四周的响应区域。
#import <UIKit/UIKit.h> @interface UIButton (EnlargeTouchAera) - (void)setEnlargeEdgeWithTop:(CGFloat) top right:(CGFloat) right bottom:(CGFloat) bottom left:(CGFloat) left; @end 下面是.m文件的实现部分,首先定义四个静态变量,是用来存储上下左右的标志。
然后重写hitTest函数,里面使用了我们自定义的enlargedRect方法。
#import "UIButton+EnlargeTouchAera.h" #import <objc/runtime.h> static char topNameKey; static char rightNameKey; static char bottomNameKey; static char leftNameKey; @implementation UIButton (EnlargeTouchAera) - (void)setEnlargeEdgeWithTop:(CGFloat)top right:(CGFloat)right bottom:(CGFloat)bottom left:(CGFloat)left { objc_setAssociatedObject(self, &topNameKey, [NSNumber numberWithFloat:top], OBJC_ASSOCIATION_COPY_NONATOMIC); objc_setAssociatedObject(self, &rightNameKey, [NSNumber numberWithFloat:right], OBJC_ASSOCIATION_COPY_NONATOMIC); objc_setAssociatedObject(self, &bottomNameKey, [NSNumber numberWithFloat:bottom], OBJC_ASSOCIATION_COPY_NONATOMIC); objc_setAssociatedObject(self, &leftNameKey, [NSNumber numberWithFloat:left], OBJC_ASSOCIATION_COPY_NONATOMIC); } - (UIView *)hitTest:(CGPoint) point withEvent:(UIEvent*) event { CGRect rect = [self enlargedRect]; if (CGRectEqualToRect(rect, self.bounds)) { return [super hitTest:point withEvent:event]; } return CGRectContainsPoint(rect, point) ? self : nil; } - (CGRect)enlargedRect { NSNumber * topEdge = objc_getAssociatedObject(self, &topNameKey); NSNumber * rightEdge = objc_getAssociatedObject(self, &rightNameKey); NSNumber * bottomEdge = objc_getAssociatedObject(self, &bottomNameKey); NSNumber * leftEdge = objc_getAssociatedObject(self, &leftNameKey); if (topEdge && rightEdge && bottomEdge && leftEdge) { return CGRectMake(self.bounds.origin.x - leftEdge.floatValue, self.bounds.origin.y - topEdge.floatValue, self.bounds.size.width + leftEdge.floatValue + rightEdge.floatValue, self.bounds.size.height + topEdge.floatValue + bottomEdge.floatValue); } else { return self.bounds; } } @end