如何扩大UIGestureRecognizer的命中区域?

Tes*_*act 11 iphone cocoa-touch uikit ipad ios

我在一些视图上使用的手势识别器很少,但有时视图太小而且难以击中它.使用识别器是必要的,那么如何扩大命中区域?

rma*_*ddy 22

如果您为自定义执行此操作UIView,则应该能够覆盖该hitTest:withEvent:方法:

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

    return CGRectContainsPoint(frame, point) ? self : nil;
}
Run Code Online (Sandbox Code Playgroud)

上面的代码将在视图周围添加20点边框.点击该区域中的任何位置(或视图本身)将指示命中.

  • 我认为最好覆盖pointInside,因为hitTest在子视图上递归调用pointInside:。 (2认同)

Mar*_*ski 6

@rmaddy 的 Swift 版本回答:

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