修改UIButton响应热区

来源:互联网 发布:寻找质数的算法 python 编辑:程序博客网 时间:2024/06/14 20:46

如何修改UIButton响应区域

修改UIButton响应区域,以前处理这个需求时,是建一个view,添加手势,覆盖在需响应的区域,这种方法比较low, 可以通过新建一个分类,利用runtime来实现。

  • 新建一个UIView,覆盖在需响应的热区
  • 新建分类,利用runtime来实现

下面介绍新建分类的方法来实现热区响应扩大

.h

定义调用方法, 调用时只需设置需响应热区的上、右、下、左的值,两个不同的方法供不同场景调用:

@interface UIButton (Extension)//分别设置不同的值- (void)setEnlargeEdgeWithTop:(CGFloat) top right:(CGFloat) right bottom:(CGFloat) bottom left:(CGFloat) left;//设置同一个值- (void)setEnlargeEdge:(CGFloat) size;@end

.m

#import "UIButton+Extension.h"#import <objc/runtime.h>  //一定要导入@implementation UIButton (Extension)static char topNameKey;static char rightNameKey;static char bottomNameKey;static char leftNameKey;//设置统一的值,上、右、下、左为同一值- (void)setEnlargeEdge:(CGFloat) size{    objc_setAssociatedObject(self, &topNameKey, [NSNumber numberWithFloat:size], OBJC_ASSOCIATION_COPY_NONATOMIC);    objc_setAssociatedObject(self, &rightNameKey, [NSNumber numberWithFloat:size], OBJC_ASSOCIATION_COPY_NONATOMIC);    objc_setAssociatedObject(self, &bottomNameKey, [NSNumber numberWithFloat:size], OBJC_ASSOCIATION_COPY_NONATOMIC);    objc_setAssociatedObject(self, &leftNameKey, [NSNumber numberWithFloat:size], OBJC_ASSOCIATION_COPY_NONATOMIC);}//设置热区,可以单独设置上、右、下、左的值- (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);}//获取属性- (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;    }}//重写方法- (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;}
原创粉丝点击