UIButton小技巧—-點擊事件的範圍
起因
在開發過程中對於UIbutton的點擊事件,有時按鈕太小不能被輕易點擊到,希望放大點擊的範圍。
解決方案
通過添加Category,重寫pointInside: withEvent:
方法,通過判斷點擊的位置是否在希望響應事件所在範圍,在期望的範圍內就響應事件,不再就不響應。
代碼
#import <UIKit/UIKit.h>
@interface UIButton (TouchScope)
- (void)expandTouchScope:(UIEdgeInsets)edgeInsets;
@end
#import "UIButton+TouchScope.h"
#import <objc/runtime.h>
static NSString *expandRectXKey = @"expandRectX";
static NSString *expandRectYKey = @"expandRectY";
static NSString *expandRectWidthKey = @"expandRectWidthKey";
static NSString *expandRectHeightKey = @"expandRectHeightKey";
@implementation UIButton (TouchScope)
- (void)expandTouchScope:(UIEdgeInsets)edgeInsets {
objc_setAssociatedObject(self,
&expandRectYKey,
[NSNumber numberWithFloat:self.bounds.origin.y - edgeInsets.top],
OBJC_ASSOCIATION_COPY_NONATOMIC);
objc_setAssociatedObject(self,
&expandRectXKey,
[NSNumber numberWithFloat:self.bounds.origin.x - edgeInsets.left],
OBJC_ASSOCIATION_COPY_NONATOMIC);
objc_setAssociatedObject(self,
&expandRectWidthKey,
[NSNumber numberWithFloat:self.frame.size.width + edgeInsets.left + edgeInsets.right],
OBJC_ASSOCIATION_COPY_NONATOMIC);
objc_setAssociatedObject(self,
&expandRectHeightKey,
[NSNumber numberWithFloat:self.frame.size.height + edgeInsets.top + edgeInsets.bottom],
OBJC_ASSOCIATION_COPY_NONATOMIC);
}
- (CGRect)expandRect {
NSNumber *expandRectX = objc_getAssociatedObject(self, &expandRectXKey);
NSNumber *expandRectY = objc_getAssociatedObject(self, &expandRectYKey);
NSNumber *expandRectWidth = objc_getAssociatedObject(self, &expandRectWidthKey);
NSNumber *expandRectHeight = objc_getAssociatedObject(self, &expandRectHeightKey);
return CGRectMake(expandRectX.floatValue,
expandRectY.floatValue,
expandRectWidth.floatValue,
expandRectHeight.floatValue);
}
// 響應用戶的點擊事件
- (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event {
CGRect buttonRect = [self expandRect];
if (CGRectEqualToRect(buttonRect, self.bounds)) {
return [super pointInside:point withEvent:event];
}
return CGRectContainsPoint(buttonRect, point) ? YES : NO;
}
@end
應用
[button expandTouchScope:UIEdgeInsetsMake(20, 20, 20, 20)];
紅色區域爲Button,藍色區域是向外拓展的20的點擊範圍。設置完成在藍色、紅色範圍內都可以響應事件。