首页 > 解决方案 > 获取 onLongPressGesture 持续时间的值

问题描述

我想知道如何获得 LongPressGesture 的持续时间。

我的目标是能够根据这个 LongGesture 按比例修改变量。

我试图引入一个@State var,以便通过 .onChanged / .onEnded 方法获取值,但是这个返回 LongGesture 的布尔值

这是我的代码(不编译):

struct ContentView: View { 
    // Well, this var @State is a CGFloat because I think that the duration is of this type (based on the minimumDuration) 
   @State var timeLongGesture: CGFloat = 0
   @State var value: Int = 1
   var body: some View { 
   // Some stuff here
   Text("Increase the value") 
   .onTapGesture { value += 1 } 
   .gesture(
       LongPressGesture(minimumDuration: 0.4)
           .onEnded { valueLongPress in
              // Here the error, because the value of "valueLongPress" is a Bool (as the doc mentionned)
              timeLongGesture = valueLongPress
            })

我觉得这很棘手。因此,如果有人有任何想法,我会接受 :-) 感谢您的帮助。

标签: xcodeswiftui

解决方案


This is how I would get the duration of an LongPressGesture:

class InitialTime: ObservableObject {
    @Published var initTime = Date()
}

struct ContentView: View {

@ObservedObject var kickoff = InitialTime()

@State var timeLongGesture: Double = 0.0
@State var value: Int = 1
@GestureState var isDetectingLongPress = false

var body: some View {
    // Some stuff here
    Text("Increase the value")
        .onTapGesture { self.value += 1 }
        .gesture(LongPressGesture(minimumDuration: 3)
            .updating($isDetectingLongPress) { _, _, _ in
                self.kickoff.initTime = Date()
                print("--------> self.kickoff.initTime: \(self.kickoff.initTime)")
        }
        .onEnded { finished in
            self.timeLongGesture = Date().timeIntervalSince(self.kickoff.initTime)
            print("-----> timeLongGesture: \(self.timeLongGesture)")
        })
}
}

推荐阅读