swift - 如何在 SwiftUI 上使 LongPressGesture 失败

标签 swift swiftui uigesturerecognizer uilongpressgesturerecogni

当我将手指从图像上移开时,我试图以最大距离使 LongPressGesture 失败,但这不起作用,它会继续打印消息“Pressed”

struct ContentView: View {
@GestureState private var isDetectingPress = false

var body: some View {
    Image(systemName: "trash")
        .resizable().aspectRatio(contentMode: .fit)
        .frame(width: 100, height: 100)
        .scaleEffect(isDetectingPress ? 0.5 : 1)
        .animation(.easeInOut(duration: 0.2))
        .gesture(LongPressGesture(minimumDuration: 0.01, maximumDistance: 10).sequenced(before:DragGesture(minimumDistance: 0).onEnded {_ in
            print("Pressed")
        })
            .updating($isDetectingPress) { value, state, _ in
                switch value {
                    case .second(true, nil):
                        state = true
                    default:
                        break
                }
        })
    }
}

最佳答案

更改您的更新修饰符以检测是否存在拖动量:

.updating($isDetectingPress) { value, state, _ in
    switch value {
    case .second(true, nil):
        state = true
    case .second(true, _): // add this case to handle `non-nil` drag amount
        state = false
    default:
        break
    }

并在 DragGesture 本身中设置 DragGesture 的最小距离(例如 100):

DragGesture(minimumDistance: 100)

而不是在LongPressGesture中:

//LongPressGesture(minimumDuration: 0.01, maximumDistance: 100) // remove `maximumDistance`
LongPressGesture(minimumDuration: 0.01)

关于swift - 如何在 SwiftUI 上使 LongPressGesture 失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63199102/

相关文章:

objective-c - 检测平移手势结束

ios - 我不明白为什么这个 @selector 不起作用

ios - Aspect 在自定义圆形 UIButton 中填充图像(图像将由用户更新)

ios - 点击保存按钮时获取表格 View 单元格中的文本字段并存储在字典中?

swiftui - 带有 SwiftUI 的 Google 地方自动完成 API

ios - 在文本中添加无限行(SwiftUI)

ios - 自定义标注手势识别

swift - 具有通用协议(protocol) swift 的工厂

ios - Swift - 使用 Segue 将数据从容器传递到 TableViewController

swiftui - 是否有可能在 SwiftUI 中停用按钮?