[英]Swift Programmatically Launch a UILongPressGesture
我想在用戶觸摸按鈕時以編程方式啟動UILongPressGesture
。 這是幾年前問的, 我如何以編程方式發送UILongPressGesture? 但我想知道是否有更清潔或更現代的解決方案。
我現有的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
),然后使用該新手勢繼續懸停動畫邏輯。
我找到了一個更清晰的解決方案來解決手頭的問題 - 用包含自己的UILongPressGestureRecognizer
的UIView
替換所需的按鈕。 我將此手勢的minimumPressDuration
設置為0,因此它的行為與按鈕的touchDown
事件等效。 這個新手勢使用原始問題中相同的longPress
函數,無需觸發任何其他代碼。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.