首页 > 解决方案 > Get time pressed in UILongPressGestureRecognizer

问题描述

I'm trying to get the time that a UIView is pressed, using UILongPressGestureRecognizer

But, the states of press:UILongPressGestureRecognizer are .began, .end, .cancelled, .changed.

But, I'm trying to know if has x seconds pressed to change the control of the UIView.

My current code is:

 override func viewDidLoad() {
        super.viewDidLoad()

        let longPressRecognizer = UILongPressGestureRecognizer(target: self, action: #selector(NavigationViewController.displayDebugger(_:)))
        self.view.addGestureRecognizer(longPressRecognizer)

    }

    @objc public func displayDebugger(_ press:UILongPressGestureRecognizer){
        if press.state == .began{
            startDate = Date()
        }
        else if press.state == .ended{
            endDate = Date()

            let components = Calendar.current.dateComponents([.second], from: startDate, to: endDate)
            if(components.second! >= 1){
                let debugger = LogView()
                debugger.loadRequests()
            }

        }
    }

But, I don't find the way to know the pressed time. Exist a way to do it?

标签: iosswiftuilongpressgesturerecogni

解决方案


当长按开始时,记下时间(开始)。当它取消、完成或失败时;可选地计算从开始的秒数。如果按下持续时间超过 5 秒,则 myView 为红色。

class MyViewController : UIViewController {

  var start: Date?

  override func loadView() {
    view = UIView()
    view.isUserInteractionEnabled = true
    view.addGestureRecognizer(UILongPressGestureRecognizer(target: self, action: #selector(tap)))
  }

  @objc func tap(gr: UILongPressGestureRecognizer) {
    switch gr.state {
    case .began:
      start = Date()
    case .failed, .cancelled, .ended:
      guard let temp = start else { return }
      let seconds = Date().timeIntervalSince(temp)
      if seconds > 5 { myView.backgroundcolor = UIColor.red }
      print(seconds)
    default:
      break
    }
  }
}

推荐阅读