SwiftUI中如何在拖拽超过100px时取消DragGesture?
实现拖拽超过100px时结束手势的可行方案
你可以通过状态变量控制手势的激活状态,达到拖拽超过阈值时自动结束手势的效果,具体实现如下:
@State private var dragOffset = CGSize.zero @State private var isDragActive = true var body: some View { // 替换成你需要添加拖拽效果的视图 Text("拖拽我") .font(.title) .padding() .background(Color.blue) .foregroundColor(.white) .cornerRadius(8) .offset(dragOffset) .gesture( DragGesture(minimumDistance: 0) .updating($dragOffset) { value, state, transaction in guard isDragActive else { return } state = value.translation // 检测拖拽横向距离是否超过100px if abs(value.translation.width) > 100 { isDragActive = false } } .onEnded { gesture in // 重置激活状态,保证下次能正常触发拖拽 isDragActive = true // 根据拖拽距离执行反馈 if abs(gesture.translation.width) > 100 { UINotificationFeedbackGenerator().notificationOccurred(.error) } else { UINotificationFeedbackGenerator().notificationOccurred(.success) } // 可选:拖拽结束后重置视图位置 dragOffset = .zero } // 当激活状态为false时,禁用手势,触发onEnded .disabled(!isDragActive) ) }
逻辑说明
- 用
isDragActive变量控制手势的启用状态,一旦拖拽距离超过100px,就将其设为false - 通过
.disabled(!isDragActive)让手势立刻失效,系统会自动调用onEnded闭包 - 在
onEnded里重置isDragActive,避免后续无法触发拖拽手势 - 替换
@GestureState为@State,因为我们需要主动控制状态的生命周期,而@GestureState会在手势结束后自动重置,不适合用来控制激活状态
内容的提问来源于stack exchange,提问作者guidev
相关产品推荐
相关产品推荐

