iOS扩大button点击范围的两种方式

UI给的图有时候小,或者需求是扩大button的点击区域,一般操作是改变button的size,还有就是不改变frame的情况下单独扩大button的点击区域。

第一种方法:继承UIButton,重写以下方法

-(BOOL)pointInside:(CGPoint)point withEvent:(UIEvent*)event
{
    CGRect bounds = self.bounds;
    //扩大原热区直径至26,可以暴露个接口,用来设置需要扩大的半径。
    CGFloat widthDelta = MAX(26, 0);
    CGFloat heightDelta = MAX(26, 0);
    bounds = CGRectInset(bounds, -0.5 * widthDelta, -0.5 * heightDelta);
    return CGRectContainsPoint(bounds, point);
}

第二种方法:重写以下方法

- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event
{
    CGRect rectBig = CGRectInset(self.bounds, -(27.0/2), -(27.0/2));
    
    if (CGRectContainsPoint(rectBig, point)) {
        return self;
    }else{
        return nil;
    }
    
    return self;
}

上面所做的变化点击区域还是矩形,如果需要将点击区域规定在圆形范围内,可以这样做:

-(UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event{
    [super hitTest:point withEvent:event];
    
    CGPoint center = CGPointMake(self.bounds.size.width/2, self.bounds.size.height/2);
    
    
   //当然这个半径也可以扩大
    CGFloat raidus = self.frame.size.height >= self.frame.size.width ?self.frame.size.width/2 :self.frame.size.width/2;
    
   //传入中心点 实时点击点 与半径判断 点击点是否在半径区域内
    BOOL pointInRound =[self touchPointInsideCircle:center radius:raidus targetPoint:point];
    
    if (pointInRound) {
        return self;
    }else
    {
        return nil;
    }
}

//用来判断 圆形点击区域
- (BOOL)touchPointInsideCircle:(CGPoint)center radius:(CGFloat)radius targetPoint:(CGPoint)point
{
    CGFloat dist = sqrtf((point.x - center.x) * (point.x - center.x) +
                         (point.y - center.y) * (point.y - center.y));
    return (dist <= radius);
}

你可能感兴趣的:(iOS扩大button点击范围的两种方式)