扩大UIButton的可点击范围

通过重写pointInside:withEvent:方法,可以实现在不改变UIButton大小的情况下,扩大其点击感应范围,本文详细介绍如何操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一般来说按钮的点击范围和按钮的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
來源:简书
简书著作权归作者所有,任何形式的转载都请联系作者获得授权并注明出处。

https://www.jianshu.com/p/e16e0cf3f764

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值