[英]Resolve UITapGestureRecognizer and UILongPressGestureRecognizer simultaneously and fire UIGestureRecognizer.State.began on finger touch down
首先,所有已經回答的問題都對我沒有幫助
該代碼幾乎可以正常工作,只有一件事:長按手勢僅在我將手指從屏幕上抬起時調用。 但是我需要表現出類似Instagram Stories中的行為(當您可以在故事之間切換並按住手指來暫停某些故事時)。
我的問題更多是關於當用戶觸摸手指而不是手指時如何強制UILongPressGesture觸發。
這是我的代碼:
private func setupTapGestures() {
tapRecognizer = UITapGestureRecognizer()
tapRecognizer?.addTarget(self, action: #selector(handleTapGesture(_:)))
tapRecognizer?.delegate = self
view.addGestureRecognizer(tapRecognizer!)
longPressRecognizer = UILongPressGestureRecognizer()
longPressRecognizer?.addTarget(self, action: #selector(handleLongPressGesture(_:)))
longPressRecognizer?.minimumPressDuration = 0.1
longPressRecognizer?.delegate = self
view.addGestureRecognizer(longPressRecognizer!)
}
@objc func handleTapGesture(_ gestureRecognizer: UIGestureRecognizer) {
let width = view.frame.width
let point = gestureRecognizer.location(in: view)
viewModel?.tapAction(viewWidth: width, tapPoint: point)
Swift.print("Tap gesture")
}
@objc func handleLongPressGesture(_ gestureRecognizer: UILongPressGestureRecognizer) {
if gestureRecognizer.state == .began {
Swift.print("Began")
} else if gestureRecognizer.state == .ended {
Swift.print("Ended")
}
}
UIGestureRecognizerDelegate :
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRequireFailureOf otherGestureRecognizer: UIGestureRecognizer) -> Bool {
// Don't recognize a single tap until a long-press fails
if gestureRecognizer == tapRecognizer && otherGestureRecognizer == longPressRecognizer {
return true
}
return false
}
有什么建議或想法嗎?
我想知道您的shouldRequireFailureOf
實施是否引起問題?
這對我來說效果很好(請注意:我使用.minimumPressDuration = 0.25
因為在0.1秒內.minimumPressDuration = 0.25
它有點困難):
class GestureTestViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
setupTapGestures()
}
private func setupTapGestures() -> Void {
let singleTapGesture = UITapGestureRecognizer(target: self, action: #selector(handleTapGesture(_:)))
view.addGestureRecognizer(singleTapGesture)
let longPressGesture = UILongPressGestureRecognizer(target: self, action: #selector(handleLongPressGesture(_:)))
longPressGesture.minimumPressDuration = 0.25
view.addGestureRecognizer(longPressGesture)
}
@objc func handleLongPressGesture(_ gesture: UILongPressGestureRecognizer) -> Void {
if gesture.state == .began {
print("Did Long Press (began)")
}
if gesture.state == .ended {
print("Did Long Press (ended)")
}
}
@objc func handleTapGesture(_ gesture: UITapGestureRecognizer) -> Void {
print("Did Single Tap")
}
}
點擊時 ,在調試控制台中顯示“ Did Single Tap” 。
按住時 ,我很快會收到“開始長按(開始)”的信息 ,而在手指抬起時得到“長按(結束)的”信息
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.