Skip to content

Instantly share code, notes, and snippets.

@Abhishek9634
Created December 27, 2018 15:51
Show Gist options
  • Save Abhishek9634/c615973d44d50c938b0ec843241df078 to your computer and use it in GitHub Desktop.
Save Abhishek9634/c615973d44d50c938b0ec843241df078 to your computer and use it in GitHub Desktop.
import UIKit
import Foundation
typealias HoldActionHandler = () -> Void
class YFButton: UIButton {
var holdAction: HoldActionHandler = { }
private var timer: Timer?
private var longPressGesture = UILongPressGestureRecognizer()
override func awakeFromNib() {
super.awakeFromNib()
self.setupGesture()
}
deinit {
self.resetTimer()
self.removeGestureRecognizer(self.longPressGesture)
}
private func setupGesture() {
self.longPressGesture = UILongPressGestureRecognizer(target: self,
action: #selector(handleLongPress(_:)))
self.addGestureRecognizer(self.longPressGesture)
}
@objc private func handleLongPress(_ gesture: UILongPressGestureRecognizer) {
switch gesture.state {
case .began:
self.timer = Timer.scheduledTimer(timeInterval: 0.1,
target: self,
selector: #selector(handleTimer(_:)),
userInfo: nil,
repeats: true)
case .ended, .cancelled:
self.resetTimer()
default:
break
}
}
private func resetTimer() {
self.timer?.invalidate()
self.timer = nil
}
@objc func handleTimer(_ timer: Timer) {
self.holdAction()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment