Search code examples
iosswiftnstimer

Swift 2.0 How to detect that the user holds instead of just tapping


I am looking for a way to detect if the user is holding on the screen (Holding the screen for 1 second) I tried using a timer but i did not work. Here is the code i have right now.

var brakeTimer = NSTimer()

func update () {
    print("The user is holding the screen")   
}

override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
    var brakeTimer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: "update", userInfo: nil, repeats: true)
}


override func touchesCancelled(touches: Set<UITouch>?, withEvent event: UIEvent?) {
    brakeTimer.invalidate()
}

Solution

  • "Holding" on the interface is commonly referred to in iOS development as "Long Pressing". Here's how to set up one of those :

    let longPressRecognizer = UILongPressGestureRecognizer(target: self, action: "longPressed:")
            self.view.addGestureRecognizer(longPressRecognizer)
    
    func longPressed(sender: UILongPressGestureRecognizer)
        {
            println("longpressed")
        }
    

    As opposed to a simple tap recognizer, which will fire when the user simply taps on the screen rather than holding for a longer duration of time.

    let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: "tapped:")
            self.view.addGestureRecognizer(tapGestureRecognizer)
    
        func tapped(sender: UITapGestureRecognizer)
        {
            println("tapped")
        }