iOS有长按手势UILongPressGestureRecognizer,这个手势需要指定长按的事件,指定时间之后,触发事件
现在需要实现长按的过程中就执行某一个动作,并且中途取消长按事件可以终止动作
需要重写 UIGestureRecognizer的几个方法
1.初始化长按手势,传入长按手势结束之后需要执行的动作
```
override init(target: Any?, action: Selector?) {
super.init(target: target, action: action)
myTarget = target as AnyObject!
myAction = action
}
```
2.重写手势开始的方法,手势一开始,启动定时器,跟随长按按钮开始事件
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent) {
setUp()
}
func setUp() {
if progressTimer == nil {
progressTimer = Timer.scheduledTimer(timeInterval: 0.03, target: self, selector: #selector(self.handleTimer(_:)), userInfo: nil, repeats: true)
}
startDate = Date()
}
3.手势取消的时候,停止定时器,状态置为 possible
```
override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent) {
if self.progressTimer != nil {
self.state = .possible
//取消定时器
tearDown("Cancel")
}
}
```
4.手势结束的时候,停止定时器,状态置为 possible
```
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent) {
if self.progressTimer != nil {
if !isTriggered {
self.isEnabled = false
self.isEnabled = true
}
self.state = .possible
//取消定时器
tearDown("Cancel")
}
}
```