iOS扩大UIButton点击范围

由网上各位大神的实现方法,总结如下:
为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
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容