iOS平移手势:达到分割阈值后移动矩形的实现问题求助
解决平移手势移动矩形时的误触发与阈值判断问题
原代码核心问题
lastPanY、lastPanx为函数局部变量,每次手势触发都会重置,无法保留基准位置- 选中note的逻辑错误:通过触摸位置计算的参数匹配note,而非判断触摸点是否在note矩形内
.changed阶段重复遍历notes,效率低且冗余- 偏移量计算、方向判断逻辑错误,导致轻微移动就触发、单轴误触
- 未处理阈值触发后的基准位置更新,导致连续触发异常
修正方案与代码
首先在视图类中添加实例变量,用于记录基准位置:
var lastPanY: CGFloat = 0 var lastPanX: CGFloat = 0 var selectedNoteIndex: Int?
然后修正手势处理函数:
@objc func handlePanGesture(_ gestureRecognizer: UIPanGestureRecognizer) { let touchLocation = gestureRecognizer.location(in: self) let timeSlotWidth = bounds.width / CGFloat(numT) let noteHeight = bounds.height / CGFloat(numN) switch gestureRecognizer.state { case .began: // 遍历所有note,判断触摸点是否在note的矩形范围内 for (index, note) in notes.enumerated() { // 计算当前note对应的矩形区域 let noteY = bounds.height - CGFloat(note.note + 1) * noteHeight let noteFrame = CGRect( x: CGFloat(note.startTime) * timeSlotWidth, y: noteY, width: CGFloat(note.duration) * timeSlotWidth, height: noteHeight ) if noteFrame.contains(touchLocation) { selectedNoteIndex = index // 记录手势开始时的触摸位置作为基准 lastPanX = touchLocation.x lastPanY = touchLocation.y setNeedsDisplay() break } } case .changed: guard let selectedIndex = selectedNoteIndex, var selectedNote = notes[selectedIndex] else { return } // 计算当前触摸位置与基准位置的偏移量 let deltaX = touchLocation.x - lastPanX let deltaY = touchLocation.y - lastPanY // 处理纵向(note轴)移动 if abs(deltaY) >= noteHeight { // 判断移动方向:向下移动note编号减小,向上增大 let direction = deltaY > 0 ? -1 : 1 let newNote = selectedNote.note + direction if newNote >= 0 && newNote < numN { notes[selectedIndex].note = newNote // 更新基准Y位置,避免重复触发 lastPanY += deltaY > 0 ? noteHeight : -noteHeight setNeedsDisplay() } } // 处理横向(时间轴)移动 if abs(deltaX) >= timeSlotWidth { // 判断移动方向:向右移动startTime增大,向左减小 let direction = deltaX > 0 ? 1.0 : -1.0 let newStartTime = selectedNote.startTime + direction if newStartTime >= 0 && newStartTime <= Double(numT - Int(selectedNote.duration)) { notes[selectedIndex].startTime = newStartTime // 更新基准X位置,避免重复触发 lastPanX += deltaX > 0 ? timeSlotWidth : -timeSlotWidth setNeedsDisplay() } } case .ended, .cancelled: selectedNoteIndex = nil setNeedsDisplay() default: break } }
关键修正点说明
- 基准位置持久化:将
lastPanX、lastPanY改为实例变量,确保手势过程中保留基准值,不会每次调用重置 - 准确选中逻辑:通过计算note的实际矩形区域,判断触摸点是否在其中,替代原有的参数匹配逻辑
- 高效的选中项访问:直接使用
selectedNoteIndex获取当前选中的note,避免重复遍历数组 - 阈值触发逻辑:只有当偏移量超过单元尺寸(
noteHeight/timeSlotWidth)时才触发移动,且触发后更新基准位置,避免连续误触发 - 方向判断修正:根据触摸偏移的正负正确判断移动方向,确保note和时间轴的移动符合直观逻辑
- 边界校验完善:横向移动时考虑note的duration,避免移动后超出视图范围
内容的提问来源于stack exchange,提问作者user8058965
相关产品推荐
相关产品推荐

