当UI设计图给出的按钮尺寸较小,我们在点击按钮时发现很难点到。那此时就需要扩大按钮的点击范围,下面就给出我用的两种扩大按钮点击范围的方法。
1.重写此方法将按钮的点击范围扩大
- (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event {
CGRect bounds = self.bounds;
//扩大点击区域
bounds = CGRectInset(bounds, -50, -50);
//若点击的点在新的bounds里面就返回yes
return CGRectContainsPoint(bounds, point);
}
2.通过UIButton的分类,通过关联对象添加一个属性.h文件如下:
@interface UIButton (Touch)
@property (nonatomic, assign) UIEdgeInsets touchInset;
@end
.m文件
import "UIButton+Touch.h"
@implementation UIButton (Touch)
(void)setTouchInset:(UIEdgeInsets)touchInset {
objc_setAssociatedObject(self, @selector(touchInset), [NSValue valueWithUIEdgeInsets:touchInset], OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}(UIEdgeInsets)touchInset {
return [objc_getAssociatedObject(self, _cmd) UIEdgeInsetsValue] ;
}
- (void)load {
//静态变量在程序运行期间只被初始化一次,然后其在下一次被访问时,其值都是上次的值,其在除了这个初始化方法以外的任何地方都不能直接修改这两个变量的值,这是单例只被初始化一次的前提
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
Method originalMethod = class_getInstanceMethod(self, @selector(pointInside:withEvent:));
Method swizzledMethod = class_getInstanceMethod(self, @selector(sw_pointInside:withEvent:));
BOOL addMethod = class_addMethod(self, @selector(pointInside:withEvent:), method_getImplementation(swizzledMethod), method_getTypeEncoding(originalMethod));
if (addMethod) {
class_replaceMethod(self, @selector(pointInside:withEvent:), method_getImplementation(swizzledMethod), method_getTypeEncoding(originalMethod));
}
});
}
- (BOOL)sw_pointInside:(CGPoint)point withEvent:(UIEvent *)event {
CGRect rect = UIEdgeInsetsInsetRect(self.bounds, self.touchInset);
if (CGRectContainsPoint(rect, point)) {
return YES;
}
return NO;
}
@end
具体需要哪种方式就根据自己需要选择