SwiftUI LongPressGesture 需要很长时间才能识别 TapGesture 何时也出现

如何解决SwiftUI LongPressGesture 需要很长时间才能识别 TapGesture 何时也出现

我想识别同一项目上的 TapGestureLongPressGesture。它工作正常,但有以下例外:LongPressGesture 单独在我指定的持续时间(0.25 秒)后响应,但是当我将它与 TapGesture 结合时,它至少需要 1 秒——我找不到办法让它反应更快。这是一个演示:

enter image description here

这是它的代码:

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 秒)之外,它工作正常。

有什么想法吗?提前致谢!

解决方法

为了在项目中拥有一些适合每个人需要的多手势,Apple 没有什么比普通手势更能提供的了,将它们混合在一起以达到想要的手势有时会变得棘手,这是一种拯救,没有 > 问题或错误!

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


enter image description here


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,scaleEffect: scaleEffect))
        
    }
    
}
,

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))
    }
}
,

嗯,这并不漂亮,但效果很好。它记录每次点击/按下的开始,如果它在 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 的解决方案,我更喜欢那个!

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 <select id="xxx"> SELECT di.id, di.name, di.work_type, di.updated... <where> <if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 <property name="dynamic.classpath" value="tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams['font.sans-serif'] = ['SimHei'] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -> systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping("/hires") public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate<String
使用vite构建项目报错 C:\Users\ychen\work>npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-