Swift以编程方式启动UILongPressGesture

问题描述 投票:0回答:1

我想以编程方式在用户触摸按钮时启动UILongPressGesture。这是多年前在How can I send a UILongPressGesture programmatically?问的,但我想知道是否有更清洁或更现代的解决方案。

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

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),然后用新手势继续悬停动画逻辑。

ios swift uigesturerecognizer uilongpressgesturerecogni
1个回答
0
投票

我找到了一个更清晰的解决方案来解决手头的问题 - 用包含自己的UIViewUILongPressGestureRecognizer替换所需的按钮。我将此手势的minimumPressDuration设置为0,因此它的行为与按钮的touchDown事件等效。这个新手势使用原始问题中相同的longPress函数,无需任何其他代码来触发。

© www.soinside.com 2019 - 2024. All rights reserved.