user1651560 user1651560 - 5 months ago 21
iOS Question

How to expand the hitTest area of a UIButton without extruding it's background image?

I have set the

UIButton
's background image and put a title on it(I used
setBackgroundImage
method not
setImage
). Now I want to expand the hitTest area of a
UIButton
without extrude it's background image.

How can I do this?

Answer

Well, you could extend UIButton and override UIView's hitTest method:

- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event {
    int expandMargin = 20;
    CGRect extendedFrame = CGRectMake(0 - expandMargin , 0 - expandMargin , self.bounds.size.width + (expandMargin * 2) , self.bounds.size.height + (expandMargin * 2));
    return (CGRectContainsPoint(extendedFrame , point) == 1) ? self : nil;
}
Comments