最近分到这个任务,作为菜鸟的我 第一反应是设置按钮的frame然后 通过改变按钮图片的内边距来实现按钮点击范围增加.被同事看到后给了更好的建议.
- (void)setClickAreaWithTop:(CGFloat)top left:(CGFloat)left bottom:(CGFloat)bottom right:(CGFloat)right{
objc_setAssociatedObject(self, &topKey, [NSNumber numberWithFloat:top], OBJC_ASSOCIATION_COPY_NONATOMIC);
objc_setAssociatedObject(self, &leftKey, [NSNumber numberWithFloat:left], OBJC_ASSOCIATION_COPY_NONATOMIC);
objc_setAssociatedObject(self, &bottomKey, [NSNumber numberWithFloat:bottom], OBJC_ASSOCIATION_COPY_NONATOMIC);
objc_setAssociatedObject(self, &rightKey, [NSNumber numberWithFloat:right], OBJC_ASSOCIATION_COPY_NONATOMIC);
}
- (CGRect)clickAreaRect{
float top = [objc_getAssociatedObject(self, &topKey) floatValue];
float left = [objc_getAssociatedObject(self, &leftKey) floatValue];
float bottom = [objc_getAssociatedObject( self, &bottomKey) floatValue];
float right = [objc_getAssociatedObject(self, &rightKey) floatValue];
if (top != 0 && left != 0 && bottom != 0 && right != 0) {
return CGRectMake(self.bounds.origin.x - left, self.bounds.origin.y - top, self.bounds.size.width + left + right, self.bounds.size.height + top + bottom);
}else{
return self.bounds;
}
}
- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event{
CGRect rect = [self clickAreaRect];
if (CGRectEqualToRect(rect, self.bounds)) {
return [super hitTest:point withEvent:event];
}else{
//判断点击点是否在rect内
return CGRectContainsPoint(rect, point) ? self : nil;
}
}
其中setClick是个对象方法 可供外部访问.
使用runtime将你想要扩大上下左右的距离作为参数传进来
然后在你点击的时候 返回给你一个点击范围扩大的值
判断你点击的是否在这个扩大的值上, 是就调用点击方法