1、在自定义的view上使用hitTest:withEvent:方法可以实现
其实就是自定义view,实现hitTest:withEvent:方法,里面加入一个按钮,这就实现了放大点击范围。就是通过截断事件传递的过程来实现放大点击范围。
#import "TestView.h"
@implementation TestView
- (instancetype)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
[self loadUI];
}
return self;
}
- (void)loadUI {
self.button = [UIButton buttonWithType:UIButtonTypeCustom];
self.button.frame = CGRectMake(50, 50, 100, 100);
self.button.backgroundColor = UIColor.purpleColor;
[self.button addTarget:self action:@selector(buttonClick) forControlEvents:UIControlEventTouchUpInside];
[self addSubview:self.button];
}
// 此处拦截事件传递
- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event {
if (CGRectContainsPoint(self.bounds, point)) {
return self.button;
}
return [super hitTest:point withEvent:event];
}
- (void)buttonClick {
NSLog(@"点击");
}
2、重写pointInside方式来实现
继承UIButon,重写(BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event该方法返回一个布尔值,YES说明点击事件在按钮frame中,NO说明点击事件不在按钮的frame中,因此将按钮frame周围等距离的区域内的点击事件都返回YES,便达到了扩大响应范围的目的。
TestButton.h文件
#import <UIKit/UIKit.h>
NS_ASSUME_NONNULL_BEGIN
@interface TestButton : UIButton
@property (nonatomic, assign) CGSize touchSize;
@end
NS_ASSUME_NONNULL_END
TestButton.m文件
#import "TestButton.h"
@implementation TestButton
- (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event {
CGRect bounds = self.bounds;
CGFloat widthDelta = MAX(self.touchSize.width - bounds.size.width, 0);
CGFloat heightDelta = MAX(self.touchSize.height - bounds.size.height, 0);
CGRect NewBounds = CGRectInset(bounds, - 0.5 * widthDelta, - 0.5 * heightDelta);
return CGRectContainsPoint(NewBounds, point);
}
@end
调用
self.button = [TestButton buttonWithType:UIButtonTypeCustom];
self.button.frame = CGRectMake(50, 100, 200, 50);
self.button.backgroundColor = UIColor.orangeColor;
[self.button addTarget:self action:@selector(click) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:self.button];
self.button.touchSize = CGSizeMake(300, 100);