有两种方法可以处理这个问题:
1.视图中
UIButton * button = [UIButton buttonWithType:UIButtonTypeCustom];
button.frame = CGRectMake(100, 100, 20, 20);
button.backgroundColor = [UIColor yellowColor];
[button addTarget:self action:@selector(testButtonAction:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:button];
button.minHitTestWidth = 180;// 点击区域宽高
button.minHitTestHeight = 180;
2.搭配类别使用
.h 文件
#import
@interface UIButton (HitAreaExpand)
@property (nonatomic) CGFloat minHitTestWidth;
@property (nonatomic) CGFloat minHitTestHeight;
@end
.m 文件
#import "UIButton+HitAreaExpand.h"
#import
@implementation UIButton (HitAreaExpand)
- (CGFloat)minHitTestWidth {
NSNumber * width = objc_getAssociatedObject(self, @selector(minHitTestWidth));
return [width floatValue];
}
- (void)setMinHitTestWidth:(CGFloat)minHitTestWidth {
objc_setAssociatedObject(self, @selector(minHitTestWidth), [NSNumber numberWithFloat:minHitTestWidth], OBJC_ASSOCIATION_ASSIGN);
}
- (CGFloat)minHitTestHeight {
NSNumber * height = objc_getAssociatedObject(self, @selector(minHitTestHeight));
return [height floatValue];
}
- (void)setMinHitTestHeight:(CGFloat)minHitTestHeight {
objc_setAssociatedObject(self, @selector(minHitTestHeight), [NSNumber numberWithFloat:minHitTestHeight], OBJC_ASSOCIATION_ASSIGN);
}
- (BOOL)pointInside:(CGPoint)point withEvent:(nullable UIEvent *)event {
return CGRectContainsPoint(HitTestingBounds(self.bounds, self.minHitTestWidth, self.minHitTestHeight), point);
}
CGRect HitTestingBounds(CGRect bounds, CGFloat minimumHitTestWidth, CGFloat minimumHitTestHeight) {
CGRect hitTestingBounds = bounds;
if (minimumHitTestWidth > bounds.size.width) {
hitTestingBounds.size.width = minimumHitTestWidth;
hitTestingBounds.origin.x -= (hitTestingBounds.size.width - bounds.size.width)/2;
}
if (minimumHitTestHeight > bounds.size.height) {
hitTestingBounds.size.height = minimumHitTestHeight;
hitTestingBounds.origin.y -= (hitTestingBounds.size.height - bounds.size.height)/2;
}
return hitTestingBounds;
}
@end