Swift 以编程方式启动 UILongPressGesture [英] Swift Programmatically Launch a UILongPressGesture

查看:28
本文介绍了Swift 以编程方式启动 UILongPressGesture的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在用户触摸按钮时以编程方式启动 UILongPressGesture.这是多年前在 如何以编程方式发送 UILongPressGesture 的问题? 但我想知道是否有更干净或更现代的解决方案.

I would like to programmatically launch a UILongPressGesture when a user touches a button. This was asked years ago at How can I send a UILongPressGesture programmatically? but I'm wondering if there's a cleaner or more modern solution.

我现有的 UILongPressGestureRecognizer 代码(将实际用户交互映射到功能)的工作方式如下:

My existing UILongPressGestureRecognizer code (which maps actual user interactions to functionality) works as follows:

view.addGestureRecognizer(UILongPressGestureRecognizer(target: self, action: #selector(longPress)))

其中 longPress 定义为:

@objc func longPress(sender: UILongPressGestureRecognizer) {
    switch sender.state {
    case .began:
        // Display a 'hover' animation for a specific UIView
        ....
    case .changed:
        // Move existing hover animation
        ...
    default:
        // Complete the hover animation
        ...
    }
}

所需的功能

我使用这个长按来为用户选择的任何 UIView 显示悬停"效果.我还想提供一个按钮来自动开始长按(绕过 longPress 其中 sender.state == .began).我计划的解决方案是以编程方式创建 .began 长按,创建一个用户可以在屏幕上拖动的手势对象(甚至可能将 UILongPressGestureRecognizer 转换为 UIPanGestureRecognizer(如果可能),然后使用该新手势继续悬停动画逻辑.

I am using this long press to display a 'hovering' effect for whatever UIView is selected by the user. I also want to provide a button to start the long press automatically (bypassing the longPress where sender.state == .began). My projected solution is programmatically creating the .began long press, creating a gesture object that users can drag around the screen (possibly even translating the UILongPressGestureRecognizer to a UIPanGestureRecognizer if possible), and then continuing the hover animation logic with that new gesture.

推荐答案

我找到了一个更简洁的解决方案 - 用包含自己的 UILongPressGestureRecognizer 的 UIView 替换所需的按钮.我将此手势的 minimumPressDuration 设置为 0,因此它的行为等同于按钮的 touchDown 事件.这个新手势使用与原始问题相同的 longPress 函数,无需任何额外的代码来触发.

I found a much cleaner solution to the problem at hand - Replacing the desired button with a UIView containing its own UILongPressGestureRecognizer. I set this gesture's minimumPressDuration to 0 so it behaves equivalently to a button's touchDown event. This new gesture uses the same longPress function from the original question without requiring any additional code to trigger.

这篇关于Swift 以编程方式启动 UILongPressGesture的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆