iOS三种方法-增大Button的点击范围

方法一:

继承UIButton

使用方法:直接继承使用

#import 
@interface LPBgFrameButton : UIButton
@end

#import "LPBgFrameButton.h"
@implementation LPBgFrameButton
- (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent*)event{
   CGRect bounds = self.bounds;
   //若原热区小于44x44,则放大热区,否则保持原大小不变
   CGFloat widthDelta = MAX(44.0 - bounds.size.width, 0);
   CGFloat heightDelta = MAX(44.0 - bounds.size.height, 0);
   bounds = CGRectInset(bounds, -0.5 * widthDelta, -0.5 * heightDelta);
   return CGRectContainsPoint(bounds, point);
}
@end

方法二:(推荐使用)

UIButton分类

使用方法:button控件调用

[button setHitTestEdgeInsets:UIEdgeInsetsMake(-50, - 50, -50, - 50)];


#import 
@interface UIButton (BigFream)
@property(nonatomic, assign) UIEdgeInsets hitTestEdgeInsets;
@end

#import "UIButton+BigFream.h"
#import 
@implementation UIButton (BigFream)
@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);
}

方法三:

改变图片的内边距

(增大button.frame,减小button.imageEdgeInsets)
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
button.frame = CGRectMake(0, 0, 40, 40);
button.center= CGPointMake(self.view.frame.size.width/2, self.view.frame.size.height/4*3);
button.backgroundColor = [UIColor yellowColor];
button.imageEdgeInsets = UIEdgeInsetsMake(10, 10, 10, 10);
[button setImage:[UIImage imageNamed:@"new_feature_1"] forState:UIControlStateNormal];
button.tag = 23;
[button addTarget:self action:@selector(onClick:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:button];

你可能感兴趣的:(iOS三种方法-增大Button的点击范围)