自定义长按手势识别器

时间:2017-07-27 00:05:24

标签: ios swift

我想通过以下方式自定义长按手势识别器:

1)当我按住一个物体0.5秒时,物体变暗,然后 2)当我继续按住对象一秒钟(总共1.5秒)时,会发生一些动作(例如对象消失)。

基本上,通过按住对象至少1.5秒,两个动作分别在两个时间发生。我也有一个轻敲手势识别器,可能会影响事物。

2 个答案:

答案 0 :(得分:2)

请参阅Reinier's solution,因为它是正确的。这个增加了延迟以满足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")
}

答案 1 :(得分:2)

来自@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
}
}

希望这个帮助

相关问题