ios SwiftUI LongPressGesture在TapGesture也存在时需要太长时间才能识别

57hvy0tb  于 2023-06-25  发布在  iOS
关注(0)|答案(4)|浏览(148)

我想在同一个项目上识别一个TapGestureLongPressGesture。它工作得很好,除了以下几个例外:LongPressGesture在我指定的持续时间(0.25秒)之后单独响应,但是当我将它与TapGesture结合使用时,它至少需要1秒-我无法找到使其响应更快的方法。下面是一个demo:

下面是它的代码:

struct ContentView: View {
    @State var message = ""

    var body: some View {
        Circle()
            .fill(Color.yellow)
            .frame(width: 150, height: 150)
            .onTapGesture(count: 1) {
                message = "TAP"
            }
            .onLongPressGesture(minimumDuration: 0.25) {
                message = "LONG\nPRESS"
            }
            .overlay(Text(message)
                        .font(.title).bold()
                        .multilineTextAlignment(.center)
                        .allowsHitTesting(false))
    }
}

请注意,除了LongPress的持续时间远长于0.25秒之外,它工作正常。
有什么想法吗?提前感谢!

iezvtpos

iezvtpos1#

要有一些多手势,以满足每个人的需要在项目中,苹果没有什么比正常手势提供,混合他们在一起达到愿望手势有时会变得棘手,这里是一个拯救,工作没有问题或bug!

  • 这里有一个自定义的零问题手势,名为interactionReader,我们可以将其应用于任何View。* * 同时拥有LongPressGestureTapGesture**。*

import SwiftUI

struct ContentView: View {
    
    var body: some View {
        
        Circle()
            .fill(Color.yellow)
            .frame(width: 150, height: 150)
            .interactionReader(longPressSensitivity: 250, tapAction: tapAction, longPressAction: longPressAction, scaleEffect: true)
            .animation(Animation.easeInOut(duration: 0.2))
        
    }
    
    func tapAction() { print("tap action!") }
    
    func longPressAction() { print("longPress action!") }
    
}
struct InteractionReaderViewModifier: ViewModifier {
    
    var longPressSensitivity: Int
    var tapAction: () -> Void
    var longPressAction: () -> Void
    var scaleEffect: Bool = true
    
    @State private var isPressing: Bool = Bool()
    @State private var currentDismissId: DispatchTime = DispatchTime.now()
    @State private var lastInteractionKind: String = String()
    
    func body(content: Content) -> some View {
        
        let processedContent = content
            .gesture(gesture)
            .onChange(of: isPressing) { newValue in
                
                currentDismissId = DispatchTime.now() + .milliseconds(longPressSensitivity)
                let dismissId: DispatchTime = currentDismissId
                
                if isPressing {
                    
                    DispatchQueue.main.asyncAfter(deadline: dismissId) {
                        
                        if isPressing { if (dismissId == currentDismissId) { lastInteractionKind = "longPress"; longPressAction() } }
                        
                    }
                    
                }
                else {
                    
                    if (lastInteractionKind != "longPress") { lastInteractionKind = "tap"; tapAction() }
                    
                    DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(50)) {lastInteractionKind = "none"}
                    
                    
                }
                
            }
        
        return Group {
            
            if scaleEffect { processedContent.scaleEffect(lastInteractionKind == "longPress" ? 1.5: (lastInteractionKind == "tap" ? 0.8 : 1.0 )) }
            else { processedContent }
            
        }

    }
    
    var gesture: some Gesture {
        
        DragGesture(minimumDistance: 0.0, coordinateSpace: .local)
            .onChanged() { _ in if !isPressing { isPressing = true } }
            .onEnded() { _ in isPressing = false }
        
    }
    
}
extension View {
    
    func interactionReader(longPressSensitivity: Int, tapAction: @escaping () -> Void, longPressAction: @escaping () -> Void, scaleEffect: Bool = true) -> some View {
        
        return self.modifier(InteractionReaderViewModifier(longPressSensitivity: longPressSensitivity, tapAction: tapAction, longPressAction: longPressAction, scaleEffect: scaleEffect))
        
    }
    
}
zzlelutf

zzlelutf2#

我发现了这个老问题,既然我不得不做类似的事情,我想我应该分享一下。最后我得到了这段代码,只要它没有附加到Button(它吸收了一些手势),它似乎工作得很好。把下面的代码加到一个图像或圆圈之类的东西上,它会立即检测到一个点击,或者在0.25秒后长按。(请注意,这将仅检测一个或另一个,而不是两者。

.onTapGesture(count: 1) {
        print("Tap Gesture. \(Date().timeIntervalSince1970)")
      }
      .simultaneousGesture(
        LongPressGesture(minimumDuration: 0.25)
          .onEnded() { value in
            print("LongPressGesture started. \(Date().timeIntervalSince1970)")
          }
          .sequenced(before:TapGesture(count: 1)
            .onEnded {
              print("LongPressGesture ended. \(Date().timeIntervalSince1970)")
            }))

我想你之前问题的根源是轻击手势必须“掉穿”到长按手势,这花了一点时间。这一个同时开始,但只有一个成功。

kxxlusnw

kxxlusnw3#

LongPressGesture有另一个完成,当用户第一次触摸时,它可以执行一个动作。并且再次以最小持续时间进行。这样的东西能起作用吗?

struct LongTapTest: View {
    @State var message = ""

    var body: some View {
        Circle()
            .fill(Color.yellow)
            .frame(width: 150, height: 150)
            .onLongPressGesture(minimumDuration: 0.25, maximumDistance: 50, pressing: { (isPressing) in
            if isPressing {
                // called on touch down
            } else {
                // called on touch up
                message = "TAP"
            }
        }, perform: {
            message = "LONG\nPRESS"
        })
            .overlay(Text(message)
                        .font(.title).bold()
                        .multilineTextAlignment(.center)
                        .allowsHitTesting(false))
    }
}
xoshrz7s

xoshrz7s4#

这不是很漂亮,但它工作得很好。它记录每次点击/按下的开始,如果在0.25秒之前结束,它将其视为TapGesture,否则它将其视为LongPressGesture

struct ContentView: View {
    @State var pressInProgress = false
    @State var gestureEnded = false
    @State var workItem: DispatchWorkItem? = nil
    @State var message = ""

    var body: some View {

        Circle()
            .fill(Color.yellow)
            .frame(width: 150, height: 150, alignment: .center)
            .overlay(Text(message)
                         .font(.title).bold()
                         .multilineTextAlignment(.center)
                         .allowsHitTesting(false))
            .gesture(
                DragGesture(minimumDistance: 0, coordinateSpace: .global)
                    .onChanged { _ in
                        guard !pressInProgress else { return }
                        pressInProgress = true
                        workItem = DispatchWorkItem {
                            message = "LONG\nPRESSED"
                            gestureEnded = true
                        }
                        DispatchQueue.main.asyncAfter(deadline: .now() + 0.25, execute: workItem!)
                }
                .onEnded { _ in
                    pressInProgress = false
                    workItem?.cancel()
                    guard !gestureEnded else { // moot if we're past 0.25 seconds so ignore
                        gestureEnded = false
                        return
                    }
                    message = "TAPPED"
                    gestureEnded = false
                }
        )
    }
}

如果有人能想到一个实际使用LongPressGestureTapGesture的解决方案,我会更喜欢!

相关问题