美文网首页
增大UIButton的点击热区

增大UIButton的点击热区

作者: Iamyu | 来源:发表于2021-02-05 09:53 被阅读0次

    有两种方法可以处理这个问题:

    1.视图中

        UIButton * button = [UIButton buttonWithType:UIButtonTypeCustom];

        button.frame = CGRectMake(100, 100, 20, 20);

        button.backgroundColor = [UIColor yellowColor];

        [button addTarget:self action:@selector(testButtonAction:) forControlEvents:UIControlEventTouchUpInside];

        [self.view addSubview:button];

        button.minHitTestWidth = 180;// 点击区域宽高

        button.minHitTestHeight = 180;

    2.搭配类别使用

    .h 文件

    #import <UIKit/UIKit.h>

    @interface UIButton (HitAreaExpand)

    @property (nonatomic) CGFloat minHitTestWidth;

    @property (nonatomic) CGFloat minHitTestHeight;

    @end

    .m 文件

    #import "UIButton+HitAreaExpand.h"

    #import <objc/runtime.h>

    @implementation UIButton (HitAreaExpand)

    - (CGFloat)minHitTestWidth {

        NSNumber * width = objc_getAssociatedObject(self, @selector(minHitTestWidth));

        return [width floatValue];

    }

    - (void)setMinHitTestWidth:(CGFloat)minHitTestWidth {

        objc_setAssociatedObject(self, @selector(minHitTestWidth), [NSNumber numberWithFloat:minHitTestWidth], OBJC_ASSOCIATION_ASSIGN);

    }

    - (CGFloat)minHitTestHeight {

        NSNumber * height = objc_getAssociatedObject(self, @selector(minHitTestHeight));

        return [height floatValue];

    }

    - (void)setMinHitTestHeight:(CGFloat)minHitTestHeight {

        objc_setAssociatedObject(self, @selector(minHitTestHeight), [NSNumber numberWithFloat:minHitTestHeight], OBJC_ASSOCIATION_ASSIGN);

    }

    - (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

    相关文章

      网友评论

          本文标题:增大UIButton的点击热区

          本文链接:https://www.haomeiwen.com/subject/ilebtltx.html