#import <UIKit/UIKit.h> @interface UIButton (HitEdgeInsets) @property(nonatomic, assign) CGFloat hitTestEdgeInsets; - (void)setHitEdgeWithTop:(CGFloat)top left:(CGFloat)left bottom:(CGFloat)bottom right:(CGFloat)right; - (void)setHitEdgeWithRect; @end
#import "UIButton+HitEdgeInsets.h" @implementation UIButton (HitEdgeInsets) static char topEdgeKey; static char leftEdgeKey; static char bottomEdgeKey; static char rightEdgeKey; - (void)setHitTestEdgeInsets:(CGFloat)hitTestEdgeInsets { [self setHitEdgeWithTop:hitTestEdgeInsets left:hitTestEdgeInsets bottom:hitTestEdgeInsets right:hitTestEdgeInsets]; } - (CGFloat)hitTestEdgeInsets { //獲取相關聯的對象 return [(NSNumber *)objc_getAssociatedObject(self, &topEdgeKey) floatValue]; } - (void)setHitEdgeWithTop:(CGFloat)top left:(CGFloat)left bottom:(CGFloat)bottom right:(CGFloat)right { objc_setAssociatedObject(self, &topEdgeKey, [NSNumber numberWithFloat:top], OBJC_ASSOCIATION_RETAIN_NONATOMIC); objc_setAssociatedObject(self, &leftEdgeKey, [NSNumber numberWithFloat:left], OBJC_ASSOCIATION_RETAIN_NONATOMIC); objc_setAssociatedObject(self, &bottomEdgeKey, [NSNumber numberWithFloat:bottom], OBJC_ASSOCIATION_RETAIN_NONATOMIC); objc_setAssociatedObject(self, &rightEdgeKey, [NSNumber numberWithFloat:right], OBJC_ASSOCIATION_RETAIN_NONATOMIC); } - (void)setHitEdgeWithRect { objc_setAssociatedObject(self, &topEdgeKey, [NSNumber numberWithFloat:30], OBJC_ASSOCIATION_RETAIN_NONATOMIC); objc_setAssociatedObject(self, &leftEdgeKey, [NSNumber numberWithFloat:30], OBJC_ASSOCIATION_RETAIN_NONATOMIC); objc_setAssociatedObject(self, &bottomEdgeKey, [NSNumber numberWithFloat:30], OBJC_ASSOCIATION_RETAIN_NONATOMIC); objc_setAssociatedObject(self, &rightEdgeKey, [NSNumber numberWithFloat:30], OBJC_ASSOCIATION_RETAIN_NONATOMIC); } - (CGRect)enlargeRect { 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.width+leftEdge.floatValue+rightEdge.floatValue, self.height+topEdge.floatValue+bottomEdge.floatValue); return enlargeRect; }else { return self.bounds; } } - (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event { if (self.alpha<=0.01||!self.userInteractionEnabled||self.hidden) { return nil; } CGRect enlargeRect = [self enlargeRect]; return CGRectContainsPoint(enlargeRect, point)?self:nil; }