思路:建一个UIbutton分类,结合runtime更改按钮点击响应区域
实现代码:
.h
//
// UIButton+JhLargeTouchArea.h
// FaceChat
//
// Created by Administrator on 2018/8/1.
// Copyright © 2018年 Zanxiang. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface UIButton (JhLargeTouchArea)
/**
点击区域分别向各个方向扩展的长度
@param top 上--长度
@param left 左--长度
@param bottom 下--长度
@param right 右--长度
*/
- (void)setJhLargeEdgeWithTop:(CGFloat)top left:(CGFloat)left bottom:(CGFloat)bottom right:(CGFloat)right;
/**
点击区域分别向四周扩展的长度
@param size 长度
*/
- (void)setJhLargeEdge:(CGFloat)size;
@end
.m
//
// UIButton+JhLargeTouchArea.m
// FaceChat
//
// Created by Administrator on 2018/8/1.
// Copyright © 2018年 Zanxiang. All rights reserved.
//
#import "UIButton+JhLargeTouchArea.h"
#import <objc/objc.h>
@implementation UIButton (JhLargeTouchArea)
static char topNameKey;
static char leftNameKey;
static char bottomNameKey;
static char rightNameKey;
- (void)setJhLargeEdgeWithTop:(CGFloat)top left:(CGFloat)left bottom:(CGFloat)bottom right:(CGFloat)right{
objc_setAssociatedObject(self, &topNameKey, [NSNumber numberWithFloat:top], OBJC_ASSOCIATION_COPY_NONATOMIC);
objc_setAssociatedObject(self, &leftNameKey, [NSNumber numberWithFloat:left], OBJC_ASSOCIATION_COPY_NONATOMIC);
objc_setAssociatedObject(self, &bottomNameKey, [NSNumber numberWithFloat:bottom], OBJC_ASSOCIATION_COPY_NONATOMIC);
objc_setAssociatedObject(self, &rightNameKey, [NSNumber numberWithFloat:right], OBJC_ASSOCIATION_COPY_NONATOMIC);
}
- (void)setJhLargeEdge:(CGFloat)size{
objc_setAssociatedObject(self, &topNameKey, [NSNumber numberWithFloat:size], OBJC_ASSOCIATION_COPY_NONATOMIC);
objc_setAssociatedObject(self, &leftNameKey, [NSNumber numberWithFloat:size], OBJC_ASSOCIATION_COPY_NONATOMIC);
objc_setAssociatedObject(self, &bottomNameKey, [NSNumber numberWithFloat:size], OBJC_ASSOCIATION_COPY_NONATOMIC);
objc_setAssociatedObject(self, &rightNameKey, [NSNumber numberWithFloat:size], OBJC_ASSOCIATION_COPY_NONATOMIC);
}
- (CGRect)jhLargeRect{
NSNumber *topEdge = objc_getAssociatedObject(self, &topNameKey);
NSNumber *leftEdge = objc_getAssociatedObject(self, &leftNameKey);
NSNumber *bottomEdge = objc_getAssociatedObject(self, &bottomNameKey);
NSNumber *rightEdge = objc_getAssociatedObject(self, &rightNameKey);
if (topEdge && leftEdge && bottomEdge && rightEdge) {
return CGRectMake(self.bounds.origin.x - leftEdge.floatValue, self.bounds.origin.y - topEdge.floatValue, self.bounds.size.width+leftEdge.floatValue+rightEdge.floatValue, self.bounds.size.height+topEdge.floatValue+bottomEdge.floatValue);
}else{
return self.bounds;
}
}
- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event{
CGRect rect = [self jhLargeRect];
if (CGRectEqualToRect(rect, self.bounds)) {
return [super hitTest:point withEvent:event];
}
return CGRectContainsPoint(rect, point) ? self : nil;
}
@end
根据需求自行选择方法调用即可
网友评论