扩大UIButton 响应区域

根据设置按钮图片方法可分为两种方式

1.setImage: 设置图片内容显示模式为居中,然后再设置图片的边距和按钮的大小

[[button imageView] setContentMode: UIViewContentModeCenter];
[[button setImage:[UIImage imageNamed:@"xxx.png"] forState:UIControlStateNormal];
//根据需求设置图片与按钮周边的边距及按钮的frame
[button setImageEdgeInsets:UIEdgeInsetsMake(10, 10, 10, 10)];
button.frame = CGRectMake(30, 30, 30, 30);

2. setBackgroundImage:设置按钮背景图片上述方法就无效了,此时可以通过OC黑魔法来解决. 首先添加一个UIButton的category来重写hitTest,然后通过为分类添加的一个属性来扩大按钮的响应区域

UIButton+EnlargeHitArea.h

@interface UIButton (Extensions)
@property(nonatomic, assign) UIEdgeInsets hitTestEdgeInsets;
@end

UIButton+EnlargeHitArea.m

#import "UIButton+EnlargeHitArea.h"
#import 

@implementation UIButton (EnlargeHitArea)

@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

通过设置按钮分类的hitTestEdgeInsets属性扩大按钮的响应范围

#import "UIButton+EnlargeHitArea.h"
[button setHitTestEdgeInsets:UIEdgeInsetsMake(-10, -10, -10, -10)];

 

你可能感兴趣的:(iOS)