You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让UITapGestureRecognizer拦截视图外小范围的点击手势

实现方案

你可以通过重写UIView的point(inside:with:)方法自定义点击响应范围,不需要额外创建不可见视图,是官方推荐的点击区域调整方案,具体实现如下:

  1. 自定义可调整点击区域的视图类
class ExpandTapAreaView: UIView {
    // 配置点击区域向外扩大的边距,可按需调整数值
    var tapExpandInsets: UIEdgeInsets = .init(top: -20, left: -20, bottom: -20, right: -20)
    
    override func point(inside point: CGPoint, with event: UIEvent?) -> Bool {
        let responseArea = bounds.inset(by: tapExpandInsets)
        return responseArea.contains(point)
    }
}
  1. 使用方式
    将你原来添加点击手势的视图类替换为ExpandTapAreaView,根据你的需求调整tapExpandInsets的参数即可:负值代表对应方向向外扩大点击区域,正值代表向内缩小点击区域。

注意事项

  • 如果扩大后的点击范围超出了当前视图的父视图bounds,需要同步重写父视图的point(inside:with:)方法,否则父视图默认不会把超出自身bounds的触摸事件传递给子视图,扩大的区域不会响应点击。
  • 如果你的点击载体是UIButton,也可以用完全相同的逻辑重写UIButton的point(inside:with:)方法实现点击区域扩大。

内容的提问来源于stack exchange,提问作者crost

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 00:45:08