iOS--增大button的点击区域

开发中创建按钮,然后通过addTarget:监听按钮的点击事件。我们希望按钮的大小不变(和图片一致),希望增大按钮的点击区域。
可以通过以下方法:
1.自定义点击按钮

- (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event
{
//此处需要获取bounds,非frame
    CGRect bounds = self.bounds;
    
    CGSize maxClickSize = (self.clickSize.width != 0 && self.clickSize.height != 0)? self.clickSize : CGSizeMake(bounds.size.width * 2, bounds.size.height * 2);
    
    CGFloat widthExtenstion = MAX(maxClickSize.width - bounds.size.width, 0);
    CGFloat heightExtenstion = MAX(maxClickSize.height - bounds.size.height, 0);
    bounds = CGRectInset(bounds, -0.5 * widthExtenstion, -0.5*heightExtenstion);
    return CGRectContainsPoint(bounds, point);
}

- (void)create
{
       UIImage *buttonImg = [UIImage imageNamed:@"compose_close_button"];
        _cancelButton.cg_size = buttonImg.size;
        _cancelButton.clickSize = CGSizeMake(50, 50);
}

2.可以通过hitTest:withEvent:设置按钮的放大区域

- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event
{
    CGRect covertRect = [self convertRect:self.button.frame fromView:window];
    CGRectInset(covertRect, -10, -10);
    if(CGRectContainsPoint(covertRect, point)) {
        return button;
    }
    return [super hitTest:point withEvent:event];
}

判断点是否在rect区域时,需要转换到同一坐标系

使用建议:建议自定义按钮,需要增大点击区域,很方便使用。

你可能感兴趣的:(iOS--增大button的点击区域)