扩大button的响应区域

有的时候遇到UE设计特别严格,所给图片有点小而且要符合标注图的设计,所用有button点小的时候,点击事件不够灵敏,就需要来扩大它的相应区域了

#import <UIKit/UIKit.h>

@interface UIButton (LiEnlarged)
/**
扩大button点击区域,扩大边际区域各个边距值相同
 */
@property (nonatomic,assign) CGFloat enlargeEdge;

@end

#import "UIButton+LiEnlarged.h"
#import <objc/runtime.h>
static char topEdgeKey;
static char leftEdgeKey;
static char bottomEdgeKey;
static char rightEdgeKey;
@implementation UIButton (LiEnlarged)
-(void)setEnlargeEdge:(CGFloat)enlargeEdge
{
    [self setEnlargeEdgeWithTop:enlargeEdge left:enlargeEdge bottom:enlargeEdge right:enlargeEdge];
}
-(void)setEnlargeEdgeWithTop:(CGFloat)top left:(CGFloat)left
                      bottom:(CGFloat)bottom right:(CGFloat)right
{
    objc_setAssociatedObject(self, &topEdgeKey, [NSNumber numberWithFloat:top], 1);
    objc_setAssociatedObject(self, &leftEdgeKey, [NSNumber numberWithFloat:left], 1);
    objc_setAssociatedObject(self, &bottomEdgeKey, [NSNumber numberWithFloat:bottom], 1);
    objc_setAssociatedObject(self, &rightEdgeKey, [NSNumber numberWithFloat:right], 1);
}
-(CGFloat)enlargeEdge
{
    return [(NSNumber *)objc_getAssociatedObject(self, &topEdgeKey) floatValue];
}
-(CGRect)enlargedRect
{
    NSNumber *topEdge = objc_getAssociatedObject(self, &topEdgeKey);
     NSNumber *leftEdge = objc_getAssociatedObject(self, &leftEdgeKey);
     NSNumber *bottomEdge = objc_getAssociatedObject(self, &bottomEdgeKey);
     NSNumber *rightEdge = objc_getAssociatedObject(self, &rightEdgeKey);
    if (topEdge && leftEdge && bottomEdge && rightEdge)
    {
        CGRect enlargeRect = 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);
        return enlargeRect;
    }
    
    return self.bounds;
}
//hittest确定点击的对象
 -(UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event
{
    if (self.alpha <= 0.01 || !self.userInteractionEnabled || self.hidden)
    {
        return nil;
    }
    CGRect enlargedRect = [self enlargedRect];
    return CGRectContainsPoint(enlargedRect, point)?self:nil;
    
}
@end



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值