UIButton扩大响应区域

  • UIButton的响应区域应当不小于44x44pt

方法一

  • 继承UIButton,覆写Button的方法
  • 代码如下:
- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event {
    if (!self.userInteractionEnabled || self.isHidden || self.alpha <= 0.01) {
        return nil;
    }
    CGRect touchuRect = CGRectInset(self.bounds, -44 , -44);
    if (CGRectContainsPoint(touchuRect, point)) {
        for (UIView *subView in [self.subviews reverseObjectEnumerator]) {
            CGPoint convertedPoint = [subView convertPoint:point toView:self];
            UIView *hinTestView = [subView hitTest:convertedPoint withEvent:event];
            if (hinTestView) {
                return hinTestView;
            }
        }
        return self;
    }
    return nil;
}

方法二

  • 也是继承UIButton,覆写Button的方法
  • 代码如下:
- (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent*)event
{
    CGRect bounds = self.bounds;
    //若原热区小于44x44,则放大热区,否则保持原大小不变
    CGFloat widthDelta = MAX(44.0 - bounds.size.width, 0);
    CGFloat heightDelta = MAX(44.0 - bounds.size.height, 0);
    bounds = CGRectInset(bounds, -0.5 * widthDelta, -0.5 * heightDelta);
    return CGRectContainsPoint(bounds, point);
}

点击测试,代码如下:

- (void)viewDidLoad {
    [super viewDidLoad];

    self.view.backgroundColor = [UIColor whiteColor];
    
    // 方法一的按钮
    LXKButton *redButton = [[LXKButton alloc] initWithFrame:CGRectMake(100, 100, 2, 2)];
    redButton.backgroundColor = [UIColor redColor];
    [redButton addTarget:self action:@selector(redButtonClicked) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:redButton];
    
    // 方法二的按钮
    LXKButton2 *blackButton = [[LXKButton2 alloc] initWithFrame:CGRectMake(100, 300, 2, 2)];
    blackButton.backgroundColor = [UIColor blackColor];
    [blackButton addTarget:self action:@selector(blackButtonClicked) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:blackButton];
}

- (void)redButtonClicked {

    NSLog(@"点击红色按钮");
}

- (void)blackButtonClicked {
    
    NSLog(@"点击黑色按钮");
}

  • 写成category好吗?感觉都所有的button都被扩大的方法,而且不经过自己调用就实现不太好

你可能感兴趣的:(UIButton扩大响应区域)