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

Swift实现穿透视图识别向下滑动手势的方法

解决方案:让穿透视图识别向下滑动并传递其余触摸

你的问题核心在于:当前的PassThroughView通过point(inside:with:)返回false实现了完全穿透,但这也导致添加在它上面的手势根本无法接收到触摸事件——因为视图直接拒绝了所有触摸。我们需要调整这个逻辑,让视图在检测到可能是向下滑动的触摸时接收事件,其他情况继续穿透。

修改后的完整代码

class PassThroughView: UIView {
    // 保存我们需要识别的向下滑动手势引用
    var swipeDownGesture: UISwipeGestureRecognizer?
    
    override func point(inside point: CGPoint, with event: UIEvent?) -> Bool {
        // 只有当向下滑动手势处于"可能识别"状态时,才让视图接收触摸
        if let gesture = swipeDownGesture, gesture.state == .possible {
            return true
        }
        // 其他所有情况,让触摸穿透到下层视图
        print("Passing all touches to the next view (if any), in the view stack.")
        return false
    }
}

class MyVC: UIViewController {
    lazy var backdropView: PassThroughView = {
        let v = PassThroughView(frame: self.view.bounds)
        v.backgroundColor = .clear
        v.isUserInteractionEnabled = true
        return v
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .clear
        addGesture()
        // 记得把backdropView添加到视图层级中(原代码遗漏了这关键一步)
        view.addSubview(backdropView)
    }
    
    func addGesture() {
        let swipeDown = UISwipeGestureRecognizer(target: self, action: #selector(handleGesture))
        swipeDown.direction = .down
        backdropView.addGestureRecognizer(swipeDown)
        // 将手势赋值给视图的属性,让point(inside:)能判断当前触摸是否关联该手势
        backdropView.swipeDownGesture = swipeDown
    }
    
    @objc func handleGesture(gesture: UISwipeGestureRecognizer) -> Void {
        if gesture.direction == .down {
            print("Swipe Down")
        }
    }
}

关键逻辑说明

  1. 手势引用传递:给PassThroughView添加swipeDownGesture属性,保存我们创建的向下滑动手势实例,让视图能在触摸判断时关联到这个手势。
  2. 触摸判断逻辑:在point(inside:with:)中,只有当手势处于.possible状态(用户刚触摸屏幕,系统还在判断是否是滑动手势的阶段),我们才返回true,让视图接收这个触摸事件,这样手势识别器就能开始处理滑动动作。
  3. 穿透保持:所有非滑动相关的触摸(比如点击、其他方向滑动),视图都会返回false,让触摸事件继续向下传递给下层视图。

额外提示

  • 如果你需要支持多个特定手势,可以扩展这个逻辑,比如用数组属性保存需要识别的手势,然后在point(inside:)中检查任意一个手势处于.possible状态即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.08 20:08:18