【问题标题】:Customize long press gesture recognizer自定义长按手势识别器
【发布时间】:2017-07-27 00:05:23
【问题描述】:

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

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

基本上,按住一个对象至少 1.5 秒,两个动作在两个不同的时间发生。我还有一个点击手势识别器,这可能会影响事情。

【问题讨论】:

  • 如果用户持有超过 1.5 秒,您需要两个操作还是只需要更多时间操作?
  • @ReinierMelian 我希望这两个动作都发生。

标签: ios swift


【解决方案1】:

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

希望有帮助

【讨论】:

  • 不错。 require(toFail:) 也有效,但会增加延迟
【解决方案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")
}

【讨论】:

  • 我试过你的方法。 quickActionPress 函数会启动,但 laterActionPress 函数永远不会启动。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-03-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多