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

iOS开发:上方有遮挡视图时如何阻断接收视图的touchesMoved事件

iOS绘图视图跨区域触摸事件截断问题

我正在开发一项绘图功能,包含主画布视图以及悬浮在其上方的工具栏。我的CanvasView中实现代码如下:

final class CanvasView: UIView {

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        guard let touch = touches.first else { return }

        let currentPoint = touch.location(in: self)
        print("touch began \(currentPoint)")
    }

    override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
        guard let touch = touches.first else { return }

        let currentPoint = touch.location(in: self)

        print("touch move \(currentPoint)")
    }

}

视图控制器中同时添加画布视图与工具栏的实现代码如下:

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        let canvasView = CanvasView()
        canvasView.backgroundColor = .white
        view.addSubview(canvasView)

        canvasView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }

        let toolbarView = UIView()
        toolbarView.backgroundColor = .black.withAlphaComponent(0.7)
        view.addSubview(toolbarView)

        toolbarView.snp.makeConstraints { make in
            make.leading.trailing.bottom.equalToSuperview()
            make.height.equalTo(200.0)
        }
    }

}

运行效果如下图所示:
运行效果示意图

实际运行表现:

  • 在画布区域拖动手指时,touchesBegan与touchesMoved事件会正常打印日志
  • 手指从画布区域移动进入工具栏区域时,touchesMoved事件仍会持续触发打印,但工具栏区域本身无法触发touchesBegan事件

已知画布被工具栏遮挡时,工具栏区域不会触发画布的touchesBegan属于符合逻辑的系统表现,需要实现的效果是:从画布区域拖动手指进入工具栏区域时,阻止画布的touchesMoved事件继续触发。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.31 13:12:24