我們可以為UIButton建立一個Category,然后利用runtime的綁定屬性,來擴大響應區(qū)域。
先看一下.h文件里的仓蛆,只聲明了一個函數(shù)。使用的時候直接利用這個函數(shù)擴大四周的響應區(qū)域挎春。
#import <UIKit/UIKit.h>
@interface UIButton (EnlargeTouchAera)
- (void)setEnlargeEdgeWithTop:(CGFloat) top right:(CGFloat) right bottom:(CGFloat) bottom left:(CGFloat) left;
@end
下面是.m文件的實現(xiàn)部分看疙,首先定義四個靜態(tài)變量,是用來存儲上下左右的標志直奋。
然后重寫hitTest函數(shù)能庆,里面使用了我們自定義的enlargedRect方法。
#import "UIButton+EnlargeTouchAera.h"
#import <objc/runtime.h>
static char topNameKey;
static char rightNameKey;
static char bottomNameKey;
static char leftNameKey;
@implementation UIButton (EnlargeTouchAera)
- (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);
}
- (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;
}
- (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;
}
}
@end