iOS扩大UIButton点击范围

由网上各位大神的实现方法,总结如下:
为UIButton添加一个分类MSExtendTouchArea

#import 

@interface UIButton (MSExtendTouchArea)

- (void)extendTouchArea:(UIEdgeInsets)edgeArea;

@end
#import "UIButton+MSExtendTouchArea.h"
#import 

@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

你可能感兴趣的:(iOS扩大UIButton点击范围)