背景
在我们日常生活中,UIButton被用到各种各样的场景之中。为了展示出其小巧和美观往往都把它做的很小也就是给的size很小。这样虽然满足了美观度,但是造成了点击体验效果不好的问题。(哈哈,因为一般汉子手指太粗点不到按钮的问题)。
解决方法
1.给UIButton增加一个扩展类(UIButton(Extension)),在里面添加如下方法
@implementation UIButton (Extension)
@dynamic hitTestEdgeInsets;
static const NSString *KEY_HIT_TEST_EDGE_INSETS = @"HitTestEdgeInsets";
-(void)setHitTestEdgeInsets:(UIEdgeInsets)hitTestEdgeInsets {
NSValue *value = [NSValue value:&hitTestEdgeInsets withObjCType:@encode(UIEdgeInsets)];
objc_setAssociatedObject(self, &KEY_HIT_TEST_EDGE_INSETS, value, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
-(UIEdgeInsets)hitTestEdgeInsets {
NSValue *value = objc_getAssociatedObject(self, &KEY_HIT_TEST_EDGE_INSETS);
if(value) {
UIEdgeInsets edgeInsets; [value getValue:&edgeInsets]; return edgeInsets;
}else {
return UIEdgeInsetsZero;
}
}
- (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event {
if(UIEdgeInsetsEqualToEdgeInsets(self.hitTestEdgeInsets, UIEdgeInsetsZero) || !self.enabled || self.hidden) {
return [super pointInside:point withEvent:event];
}
CGRect relativeFrame = self.bounds;
CGRect hitFrame = UIEdgeInsetsInsetRect(relativeFrame, self.hitTestEdgeInsets);
return CGRectContainsPoint(hitFrame, point);
}
@end
2.调用的时候也异常简单,UIButton对象调hitTestEdgeInsets方法即可
UIButton *button = [[UIButton alloc] initWithFrame:CGRectZero];
//上下左右的各个方向的Insets量
[button setHitTestEdgeInsets:UIEdgeInsetsMake(-10, -10, -10, -10)];
[self.view addsubview:button];
注:这样我们点击UIButton周围的上下左右各10的位置仍然能触发UIButton点击时间。这样就做好了增加UIButton的点击范围。