有的时候遇到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