0

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?

rmaddy
  • 314,917
  • 42
  • 532
  • 579
Benjamin RD
  • 11,516
  • 14
  • 87
  • 157
  • What problem are you actually having with the code you posted? – rmaddy Jun 18 '18 at 22:48
  • I want to change the color to my `UIView` after x seconds and if the view is still pressed – Benjamin RD Jun 18 '18 at 22:50
  • So isn't it just the difference between endDate - startDate? – El Tomato Jun 18 '18 at 22:53
  • You posted code. What problem are you having with the code you posted? You already have code that appears to do what you claim you want it to do. So please explain what is wrong with that code. – rmaddy Jun 18 '18 at 22:54
  • Do you mean that you want to change the color after the person has held their finger on the view for a certain length of time? – Paulw11 Jun 19 '18 at 08:35

1 Answers1

0

When the long press begins, note the time (start). When it cancels, finishes, or fails; optionally compute the distance in seconds from the start. If the press lasted longer than 5 seconds, myView is red.

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
    }
  }
}
jnblanchard
  • 1,182
  • 12
  • 12