最近分到這個(gè)任務(wù),作為菜鳥的我 第一反應(yīng)是設(shè)置按鈕的frame然后 通過改變按鈕圖片的內(nèi)邊距來實(shí)現(xiàn)按鈕點(diǎn)擊范圍增加.被同事看到后給了更好的建議.
- (void)setClickAreaWithTop:(CGFloat)top left:(CGFloat)left bottom:(CGFloat)bottom right:(CGFloat)right{
objc_setAssociatedObject(self, &topKey, [NSNumber numberWithFloat:top], OBJC_ASSOCIATION_COPY_NONATOMIC);
objc_setAssociatedObject(self, &leftKey, [NSNumber numberWithFloat:left], OBJC_ASSOCIATION_COPY_NONATOMIC);
objc_setAssociatedObject(self, &bottomKey, [NSNumber numberWithFloat:bottom], OBJC_ASSOCIATION_COPY_NONATOMIC);
objc_setAssociatedObject(self, &rightKey, [NSNumber numberWithFloat:right], OBJC_ASSOCIATION_COPY_NONATOMIC);
}
- (CGRect)clickAreaRect{
float top = [objc_getAssociatedObject(self, &topKey) floatValue];
float left = [objc_getAssociatedObject(self, &leftKey) floatValue];
float bottom = [objc_getAssociatedObject( self, &bottomKey) floatValue];
float right = [objc_getAssociatedObject(self, &rightKey) floatValue];
if (top != 0 && left != 0 && bottom != 0 && right != 0) {
return CGRectMake(self.bounds.origin.x - left, self.bounds.origin.y - top, self.bounds.size.width + left + right, self.bounds.size.height + top + bottom);
}else{
return self.bounds;
}
}
- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event{
CGRect rect = [self clickAreaRect];
if (CGRectEqualToRect(rect, self.bounds)) {
return [super hitTest:point withEvent:event];
}else{
//判斷點(diǎn)擊點(diǎn)是否在rect內(nèi)
return CGRectContainsPoint(rect, point) ? self : nil;
}
}
其中setClick是個(gè)對(duì)象方法 可供外部訪問.
使用runtime將你想要擴(kuò)大上下左右的距離作為參數(shù)傳進(jìn)來
然后在你點(diǎn)擊的時(shí)候 返回給你一個(gè)點(diǎn)擊范圍擴(kuò)大的值
判斷你點(diǎn)擊的是否在這個(gè)擴(kuò)大的值上, 是就調(diào)用點(diǎn)擊方法