How to increase the scope of UIGestureRecognizer?

I use several gesture recognizers on some views, but sometimes the views are too small and it's hard to hit. The use of recognizers is necessary, so how can I increase the hit area?

+8
ios iphone cocoa-touch uikit ipad
source share
3 answers

If you do this for a custom UIView , you must override the hitTest:withEvent: method:

 - (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event { CGRect frame = CGRectInset(self.bounds, -20, -20); return CGRectContainsPoint(frame, point) ? self : nil; } 

The code above adds a 20-point border around the view. Clicking anywhere in this area (or on the view itself) indicates a hit.

+19
source share

If you use the UIImageView button as a button, you can use the following extension (Swift 3.0):

 extension UIImageView { open override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? { if self.isHidden || !self.isUserInteractionEnabled || self.alpha < 0.01 { return nil } let minimumHitArea = CGSize(width: 50, height: 50) let buttonSize = self.bounds.size let widthToAdd = max(minimumHitArea.width - buttonSize.width, 0) let heightToAdd = max(minimumHitArea.height - buttonSize.height, 0) let largerFrame = self.bounds.insetBy(dx: -widthToAdd / 2, dy: -heightToAdd / 2) // perform hit test on larger frame return (largerFrame.contains(point)) ? self : nil } } 

Similar to the UIButton extension here

0
source share

Fast version of @rmaddy's answer:

 override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? { let frame = self.bounds.insetBy(dx: -20, dy: -20); return frame.contains(point) ? self : nil; } 
0
source share

All Articles