之前有个需求,按钮很小会很难点到,于是就需要扩大点击区域,一个UIButton的分类和runtime能很好解决问题。
主要方法:
//各个方向扩大到相同大小,通过objc_setAssociatedObject关联到对象
- (void)setEnlargeEdge:(CGFloat) size {
objc_setAssociatedObject(self, &topNameKey, [NSNumber numberWithFloat:size], OBJC_ASSOCIATION_COPY_NONATOMIC);
objc_setAssociatedObject(self, &rightNameKey, [NSNumber numberWithFloat:size], OBJC_ASSOCIATION_COPY_NONATOMIC);
objc_setAssociatedObject(self, &bottomNameKey, [NSNumber numberWithFloat:size], OBJC_ASSOCIATION_COPY_NONATOMIC);
objc_setAssociatedObject(self, &leftNameKey, [NSNumber numberWithFloat:size], OBJC_ASSOCIATION_COPY_NONATOMIC);
}
//可指定方向扩大,通过objc_setAssociatedObject关联到对象
- (void) setEnlargeEdgeWithTop:(CGFloat) top right:(CGFloat) right bottom:(CGFloat) bottom left:(CGFloat) left
{
objc_setAssociatedObject(self, &topNameKey, [NSNumber numberWithFloat:top], OBJC_ASSOCIATION_COPY_NONATOMIC);
objc_setAssociatedObject(self, &rightNameKey, [NSNumber numberWithFloat:right], OBJC_ASSOCIATION_COPY_NONATOMIC);
objc_setAssociatedObject(self, &bottomNameKey, [NSNumber numberWithFloat:bottom], OBJC_ASSOCIATION_COPY_NONATOMIC);
objc_setAssociatedObject(self, &leftNameKey, [NSNumber numberWithFloat:left], OBJC_ASSOCIATION_COPY_NONATOMIC);
}
//然后就是扩大区域了
- (CGRect) enlargedRect
{
NSNumber* topEdge = objc_getAssociatedObject(self, &topNameKey);
NSNumber* rightEdge = objc_getAssociatedObject(self, &rightNameKey);
NSNumber* bottomEdge = objc_getAssociatedObject(self, &bottomNameKey);
NSNumber* leftEdge = objc_getAssociatedObject(self, &leftNameKey);
if(topEdge && rightEdge && bottomEdge && leftEdge)
{
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
{
returnself.bounds;
}
}
最后依然要考虑响应链的问题:
//点击的是这个区域,就响应button的事件
- (UIView*) hitTest:(CGPoint) point withEvent:(UIEvent*) event
{
CGRectrect = [selfenlargedRect];
if (CGRectEqualToRect(rect, self.bounds))
{
return[superhitTest:pointwithEvent:event];
}
returnCGRectContainsPoint(rect, point) ?self:nil;
}
网友评论