【问题标题】:Trigger action when releasing LongPressGesture SwiftUI释放 LongPressGesture SwiftUI 时触发动作
【发布时间】:2020-08-01 10:44:38
【问题描述】:

当我在 minimumDistance 内释放 LongPressGesture 时,我试图触发“按下”消息,但是当我长按图像时,此代码会立即打印出消息。我该如何解决这个问题?

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).sequenced(before:DragGesture(minimumDistance: 100).onEnded {_ in
                print("Ended")
            })
                .updating($isDetectingPress) { value, state, _ in
                    switch value {
                    case .second(true, nil):
                        state = true
                        // The message below should be printed when I release the long press
                        print("pressed")
                    case .second(true, _):
                        state = false
                        break
                    default:
                        break
                    }
            })
    }
}

【问题讨论】:

  • 不清楚你想达到什么目的?为什么需要minimumDistance: 100
  • DragGesture(minimumDistance: 0) 需要保持状态,直到您继续触摸,但它在释放手指(您按下的情况)后立即调用 onEnded,但现在它等待拖动到 100 并且失败,因此没有 onEnded。你能解释一下这种行为吗?
  • 我基本上需要在 LongPressGesture 结束但在最小距离内时执行一个动作。如果我超出了限制距离,那么我就不需要再执行这个动作了。假设我有这个“垃圾”图像并按下它,但后来我意识到我不需要松开手指来执行操作......我只需将手指移出该图像并期望不要执行我期望的操作
  • @xmetal 为什么不使用Button 代替(里面有图片)?
  • 确实是标准的按钮行为

标签: swift swiftui gesture uitapgesturerecognizer uilongpressgesturerecogni


【解决方案1】:

您可以尝试以下方法:

struct ContentView: View {
    var body: some View {
        Button(action: {
            print("Pressed")
        }) {
            Image(systemName: "trash")
                .resizable()
                .aspectRatio(contentMode: .fit)
                .frame(width: 100, height: 100)
        }
        .buttonStyle(ScalableButtonStyle())
    }
}

struct ScalableButtonStyle: ButtonStyle {
    let scaleWhenPressed: CGFloat = 0.75

    func makeBody(configuration: Configuration) -> some View {
        configuration.label
            .scaleEffect(configuration.isPressed ? scaleWhenPressed : 1.0)
    }
}

【讨论】:

  • 我太笨了...我不知道这只是一个按钮行为。这正是我一直在寻找的
  • 我只是专注于图像,却没有意识到我可以用一个按钮来做到这一点
  • @xmetal 别担心。我们都会犯错误 :) 我们就是这样学习的。
猜你喜欢
  • 2020-07-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多