iOS开发之解决热区痛点

   在进行iOS开发的过程中,经常会遇到可点击区域与显示内容的范围不一致的情况,有时要求可点击区域的范围要比可见内容的范围大;有时要求可点击区域的范围比可见内容的范围小,情形很多,这里我就不一一列举出来了,一句话总结起来就是,按钮的热区范围和按钮的可见范围存在一定的缩进关系。
  为了解决这个问题,我创建了一个category文件,为UIButton绑定了一个属性@property (nonatomic,assign) UIEdgeInsets hitTestInsets;,配置button的时候如果配置了hitTestInsets,那么就会对热区的范围产生影响,具体如下,如果想见小热区的范围,那么这个hitTestInsets的top,left,bottom,right的值大于0;若果想扩大热区的范围,那么这个hitTestInsetstop,left,bottom,right的值大于0。使用起来也是非常的简单,只要配置一下这个hitTestInsets就可以了。
源码如下:
UIButton+JKHitTest.h

#import <UIKit/UIKit.h>

@interface UIButton (JKHitTest)
//top,left,bottom,right的值大于0的时候代表热区范围减小,反之代表热区范围扩大
@property (nonatomic,assign) UIEdgeInsets hitTestInsets;
@end

UIButton+JKHitTest.m

#import "UIButton+JKHitTest.h"
#import <objc/runtime.h>

static const char *hitTestInsetsKey = "JKHitTestInsetsKey";
static const char *useHitTestInsetsKey = "JKUseHitTestInsetsKey";
@implementation UIButton (JKHitTest)

- (void)setHitTestInsets:(UIEdgeInsets)hitTestInsets{
    NSValue *value = [NSValue valueWithBytes:&hitTestInsets objCType:@encode(UIEdgeInsets)];
    objc_setAssociatedObject(self, &useHitTestInsetsKey, @(YES), OBJC_ASSOCIATION_RETAIN);
     objc_setAssociatedObject(self, &hitTestInsetsKey, value, OBJC_ASSOCIATION_RETAIN);
}

- (UIEdgeInsets)hitTestInsets{
    NSValue *value = objc_getAssociatedObject(self, &hitTestInsetsKey);
    UIEdgeInsets insets;
    [value getValue:&insets];
    return insets;
}

//扩大关闭按钮的点击区域
- (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event
{
    NSNumber *useHitTestInsets = objc_getAssociatedObject(self, &useHitTestInsetsKey);
    BOOL status = [useHitTestInsets boolValue];
    if (status) {
        CGRect bounds = self.bounds;
        CGFloat extendX = self.hitTestInsets.left + self.hitTestInsets.right;
        CGFloat extendY = self.hitTestInsets.top + self.hitTestInsets.bottom;
        bounds = CGRectOffset(bounds, self.hitTestInsets.top, self.hitTestInsets.left);
        bounds = CGRectInset(bounds, extendX, extendY);
        return CGRectContainsPoint(bounds, point);
    }
    CGRect bounds = self.bounds;
    return CGRectContainsPoint(bounds, point);
}


@end

demo下载地址:https://github.com/xindizhiyin2014/JKUIHelper
更多优质文章,可以微信扫码关注:
这里写图片描述

相关文章
相关标签/搜索