由网上各位大神的实现方法,总结如下:
为UIButton添加一个分类MSExtendTouchArea
#import <UIKit/UIKit.h>
@interface UIButton (MSExtendTouchArea)
- (void)extendTouchArea:(UIEdgeInsets)edgeArea;
@end
#import "UIButton+MSExtendTouchArea.h"
#import <objc/runtime.h>
@implementation UIButton (MSExtendTouchArea)
static char MSExtendEdgeKey;
- (void)extendTouchArea:(UIEdgeInsets)edgeArea {
objc_setAssociatedObject(self, &MSExtendEdgeKey, [NSValue valueWithUIEdgeInsets:edgeArea], OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
- (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event {
UIEdgeInsets edge = [objc_getAssociatedObject(self, &MSExtendEdgeKey) UIEdgeInsetsValue];
CGRect extendArea = self.bounds;
if (edge.left || edge.right || edge.top || edge.bottom) {
extendArea = CGRectMake(self.bounds.origin.x - edge.left,
self.bounds.origin.y - edge.top,
self.bounds.size.width + edge.left + edge.right,
self.bounds.size.height + edge.top + edge.bottom);
}
return CGRectContainsPoint(extendArea, point);
}
@end