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

SwiftUI中如何用TapGesture替代DragGesture实现点击添加指定位置线条

解决方案:将DragGesture替换为TapGesture实现点击位置生成线条

要把当前的DragGesture(minimumDistance: 0)替换为TapGesture,核心是利用TapGesture的onEnded回调获取点击位置,逻辑和你之前的实现几乎一致,只是手势类型不同。以下是具体修改步骤和代码:

修改要点

  • 直接将DragGesture替换为TapGesture,两者的onEnded回调都能获取点击的location坐标
  • 移除Button本身的action逻辑,避免手势和Button点击触发两次操作
  • 保持原有计算tappedPointY/X和添加线条的逻辑不变

修改后的完整代码

// 水平线条按钮(左侧边框)
Button(action: {}) { // 清空Button的action,避免重复触发
    Rectangle()
        .foregroundColor(.clear)
}
.frame(width: 4, height: rectangleSize.height)
.background(Color.blue)
.position(x: 4 / 2, y: rectangleSize.height / 2)
.gesture(
    TapGesture()
        .onEnded { value in
            // 获取点击位置的Y坐标,计算相对比例
            tappedPointY = value.location.y / rectangleSize.height
            addHorizontalLine()
            self.selectedId = self.id
        }
)
.zIndex(1)

// 垂直线条按钮(顶部边框)
Button(action: {}) { // 清空Button的action,避免重复触发
    Rectangle()
        .foregroundColor(.clear)
}
.frame(width: rectangleSize.width, height: 4)
.background(Color.blue)
.position(x: rectangleSize.width / 2, y: 4 / 2)
.gesture(
    TapGesture()
        .onEnded { value in
            // 获取点击位置的X坐标,计算相对比例
            tappedPointX = value.location.x / rectangleSize.width
            addVerticalLine()
            self.selectedId = self.id
        }
)
.zIndex(1)

说明

  • TapGesture的onEnded闭包中,value.location同样能拿到相对于当前按钮视图的点击坐标,和你之前用DragGesture的方式完全一致
  • 清空Button的action是因为手势已经处理了所有逻辑,如果保留原来的action,会导致点击时触发两次addHorizontalLine()/addVerticalLine()
  • 你原来的addHorizontalLine()和addVerticalLine()函数不需要任何修改,直接复用即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 22:43:14