如何扩大button的点击区域

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/StreamLine_WenLiang/article/details/79976110

1、.h


@interface UIButton (HitAreaExpand)


@property (nonatomic) CGFloat minHitTestWidth;

@property (nonatomic) CGFloat minHitTestHeight;



@end



2、.m

#import "UIButton+HitAreaExpand.h"

#import <objc/runtime.h>

static char minHitTestWidthKey;

static char minHitTestHeightKey;

@implementation UIButton (HitAreaExpand)


- (CGFloat)minHitTestWidth {

    return [objc_getAssociatedObject(self, &minHitTestWidthKey) floatValue];

}


- (void)setMinHitTestWidth:(CGFloat)minHitTestWidth {

    objc_setAssociatedObject(self, &minHitTestWidthKey, [NSString stringWithFormat:@"%f",minHitTestWidth], OBJC_ASSOCIATION_COPY);

}


- (CGFloat)minHitTestHeight {

    return [objc_getAssociatedObject(self, &minHitTestHeightKey) floatValue];

}


- (void)setMinHitTestHeight:(CGFloat)minHitTestHeight {

    objc_setAssociatedObject(self, &minHitTestHeightKey, [NSString stringWithFormat:@"%f",minHitTestHeight], OBJC_ASSOCIATION_COPY);

}


- (BOOL)pointInside:(CGPoint)point withEvent:(nullable UIEvent *)event {

    

    return CGRectContainsPoint(HitTestingBounds(self.bounds, self.minHitTestWidth, self.minHitTestHeight), point);

}


CGRect HitTestingBounds(CGRect bounds, CGFloat minimumHitTestWidth, CGFloat minimumHitTestHeight) {

    

    CGRect hitTestingBounds = bounds;

    if (minimumHitTestWidth > bounds.size.width) {

        hitTestingBounds.size.width = minimumHitTestWidth;

        hitTestingBounds.origin.x -= (hitTestingBounds.size.width - bounds.size.width)/2;

    }

    if (minimumHitTestHeight > bounds.size.height) {

        hitTestingBounds.size.height = minimumHitTestHeight;

        hitTestingBounds.origin.y -= (hitTestingBounds.size.height - bounds.size.height)/2;

    }

    return hitTestingBounds;

}


@end


3、使用时举例

  _newsBtn = [[UIButton alloc]init];

        [_newsBtn setBackgroundImage:[UIImage imageNamed:@"Notification_Icon"] forState:UIControlStateNormal];

        //增大按钮热区域

        _newsBtn.minHitTestWidth = 44;

        _newsBtn.minHitTestHeight = 44;

        [_newsBtn addTarget:self action:@selector(clickNewsBtn) forControlEvents:UIControlEventTouchUpInside];

        [self addSubview:_newsBtn];

        [_newsBtn mas_makeConstraints:^(MASConstraintMaker *make) {

            make.right.equalTo(self.mas_right).offset(-76);

            make.centerY.equalTo(_settingBtn.mas_centerY);

            make.width.height.mas_equalTo(23);

        }];


阅读更多
想对作者说点什么?

博主推荐

换一批

没有更多推荐了,返回首页