在iOS开发中,经常遇到按钮的点击区域太小,无法达到一个良好的交互效果,通过如下方式扩大点击区域:
@interface UIButton (TTExtensions)
@property (nonatomic, assign) UIEdgeInsets hitTestEdgeInsets;
@end
#import "UIButton+TTExtensions.h"
#import <objc/runtime.h>
@implementation UIButton (TTExtensions)
- (void)setHitTestEdgeInsets:(UIEdgeInsets)hitTestEdgeInsets
{
NSValue *value = [NSValue valueWithUIEdgeInsets:hitTestEdgeInsets];
objc_setAssociatedObject(self, @selector(hitTestEdgeInsets), value, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
- (UIEdgeInsets)hitTestEdgeInsets
{
NSValue *value = objc_getAssociatedObject(self, @selector(hitTestEdgeInsets));
if (value) {
UIEdgeInsets edgeInset = [value UIEdgeInsetsValue];
return edgeInset;
}
return UIEdgeInsetsZero;
}
- (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event
{
if (UIEdgeInsetsEqualToEdgeInsets(self.hitTestEdgeInsets, UIEdgeInsetsZero) || !self.enabled || self.hidden) {
return [super pointInside:point withEvent:event];
}
CGRect relativeFrame = self.bounds;
CGRect hitFrame = UIEdgeInsetsInsetRect(relativeFrame, self.hitTestEdgeInsets);
return CGRectContainsPoint(hitFrame, point);
}
@end