Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 348
Tab Avatar asked Dec 09 '22 21:12

Tab


2 Answers

A cleaner way to do this is to override pointInside.

Here's a Swift version:

override func pointInside(point: CGPoint, withEvent event: UIEvent?) -> Bool {
    let expandedBounds = CGRectInset(self.bounds, -15, -15)
    return CGRectContainsPoint(expandedBounds, point)
}
like image 147
joel.d Avatar answered Jan 22 '23 03:01

joel.d


Here's a corrected version of the accepted answer. We're using bounds instead of frame and CGRectInset instead of CGRectMake. Cleaner and more reliable.

- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event {
    return CGRectContainsPoint([self expandedBounds], point) ? self : nil;
}

- (CGRect)expandedBounds {
    return CGRectInset(self.bounds, -20, -20);
}
like image 25
Rudolf Adamkovič Avatar answered Jan 22 '23 02:01

Rudolf Adamkovič