一般来说按钮的点击范围和按钮的frame是一样的,想要修改button的点击范围,而不修改frame,可以通过以下方法。
- (BOOL)pointInside:(CGPoint)point withEvent:(nullable UIEvent *)event;
// default returns YES if point is in bounds
这个函数的用处是判断当前的点击或者触摸事件的点是否在当前的view中。而UIButton可以通过重写该方法,来实现修改点击范围。
#import "ExpendButton.h"
@implementation ExpendButton
-(BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event
{
CGRect bounds = self.bounds;
bounds = CGRectInset(bounds, -50, -50);
return CGRectContainsPoint(bounds, point);
}
@end
将该按钮的点击范围上下左右同时扩大了50,因此,点击范围的宽度 = 按钮的宽度 + 50*2;
因此,如果原来按钮的宽度是40,那么点击范围的宽度就是140。
测试一下,先在self.view上添加一个frame为CGRectMake(0, 0, 140, 140)背景为黑色的view,再添加按钮。
- (void)viewDidLoad
{
[super viewDidLoad];
UIView * view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 140, 140)];
view.backgroundColor=[UIColor blackColor];
view.center=self.view.center;
[self.view addSubview:view];
ExpendButton * btn = [[ExpendButton alloc]initWithFrame:CGRectMake(0, 0, 40, 40)];
btn.backgroundColor=[UIColor blueColor];
btn.center=self.view.center;
[btn addTarget:self action:@selector(click) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:btn];
}
-(void)click
{
NSLog(@"在点击范围内");
}
点击黑色区域,都会响应btn的点击事件。
作者:Xiah2018
链接:https://www.jianshu.com/p/e16e0cf3f764
來源:简书
简书著作权归作者所有,任何形式的转载都请联系作者获得授权并注明出处。