Catch button pressure duration

85 views Asked by At

I am building an app in which, one of the function is to press a button that will send an emotion to my server so that I can use it. The concept is easy: the longer the button is pressed, the bigger the emotion is.

In order to do that, I actually need to catch how long this button is pressed and I don't really have a serious clue about how I could do this.

I'm "new" in Swift programming that's why I'm asking for help, or just an advice! I already did the basic elements, such as creating the button, the class for my viewcontroller, the IBAction. But I read a bit about the NSTimer variables but without truly getting the point of it.

1

There are 1 answers

4
EBDOKUM On

Make a custom class, which will extend UIView and implement it as follows:

class Some: UIView{

var start: Date?
var lastDuration: TimeInterval?{
    didSet{
        // Call the methods you need
        // At this point the value of lastDuration
        // is the value you need
    }
}

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    super.touchesBegan(touches, with: event)

    self.start = Date(timeIntervalSinceNow: 0)
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
    super.touchesEnded(touches, with: event)

    if let start = self.start{
        self.lastDuration = Date(timeIntervalSinceNow: 0).timeIntervalSince(start)
    }
}
}

This should work, let me know