簡體   English   中英

自定義長按手勢識別器

[英]Customize long press gesture recognizer

我想通過以下方式自定義長按手勢識別器:

1)當我按住某個對象0.5秒時,該對象變暗; 2)當我繼續按住該對象另一秒(總計1.5秒)時,將發生某些動作(例如,對象消失)。

本質上,通過按住對象至少1.5秒鍾,在兩個不同的時間發生了兩次操作。 我還有一個輕拍手勢識別器,它可能會影響事物。

請參閱Reinier的解決方案,因為它是正確的解決方案 這增加了一個延遲來滿足require(toFail:)


您可以使用屬性minimumPressDuration設置時間(以秒為單位,默認為0.5)

let quickActionPress = UILongPressGestureRecognizer(target: self, action: #selector(ViewController.zeroFiveSecondPress(gesture:))) // 0.5 seconds by default
let laterActionPress = UILongPressGestureRecognizer(target: self, action: #selector(ViewController.oneFiveSecondPress(gesture:)))
laterActionPress.minimumPressDuration = 1.5

someView.addGestureRecognizer(quickActionPress)
someView.addGestureRecognizer(laterActionPress)

// If 1.5 detected, only execute that one
quickActionPress.require(toFail: laterActionPress)

@objc func zeroFiveSecondPress(gesture: UIGestureRecognizer) {
    // Do something
    print("0.5 press")
}

@objc func oneFiveSecondPress(gesture: UIGestureRecognizer) {
    zeroFiveSecondPress(gesture: gesture)
    // Do something else
    print("1.5 press")
}

@nathan的答案本質上很好,但是缺少細節,您需要實現UIGestureRecognizerDelegate以允許兩個手勢同時工作,所以這是我的代碼

class ViewController: UIViewController, UIGestureRecognizerDelegate{   

    override func viewDidLoad() {
    super.viewDidLoad()

    // Do any additional setup after loading the view.

    //this for .5 time
    let firstGesture = UILongPressGestureRecognizer(target: self, action: #selector(firstMethod))
    //this for 1.5
    let secondGesture = UILongPressGestureRecognizer(target: self, action: #selector(secondMethod))
    secondGesture.minimumPressDuration = 1.5
    firstGesture.delegate = self
    secondGesture.delegate = self
    self.view.addGestureRecognizer(firstGesture)
    self.view.addGestureRecognizer(secondGesture)

}

func firstMethod() {
    debugPrint("short")
}

func secondMethod() {
    debugPrint("long")
}

func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool{
    return true
}
}

希望這個幫助

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM