自长按手势识别
我想自定义长按手势识别在以下几个方面:自长按手势识别
1)当我按住对象上0.5秒,物体变暗,并 2)当我继续按住物体另一秒(总共1.5秒),发生一些动作(例如物体消失)。
本质上,通过按住一个物体至少1.5秒,两个动作发生在两个不同的时间。我也有一个轻击手势识别器,这可能会影响事物。
从@nathan答案是本质上良好,但细节缺少你需要实现UIGestureRecognizerDelegate
同时允许手势同时工作,所以这是我的代码
class ViewController: UIViewController, UIGestureRecognizerDelegate{
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
//this for .5 time
let firstGesture = UILongPressGestureRecognizer(target: self, action: #selector(firstMethod))
//this for 1.5
let secondGesture = UILongPressGestureRecognizer(target: self, action: #selector(secondMethod))
secondGesture.minimumPressDuration = 1.5
firstGesture.delegate = self
secondGesture.delegate = self
self.view.addGestureRecognizer(firstGesture)
self.view.addGestureRecognizer(secondGesture)
}
func firstMethod() {
debugPrint("short")
}
func secondMethod() {
debugPrint("long")
}
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool{
return true
}
}
希望ŧ他的帮助
不错。 'require(toFail:)'也起作用,但增加了延迟 – nathan
请参阅Reinier's solution,因为它是正确的。这其中增加了一个延迟,以满足require(toFail:)
可以使用属性minimumPressDuration
设定的定时(以秒计,默认是0.5)
let quickActionPress = UILongPressGestureRecognizer(target: self, action: #selector(ViewController.zeroFiveSecondPress(gesture:))) // 0.5 seconds by default
let laterActionPress = UILongPressGestureRecognizer(target: self, action: #selector(ViewController.oneFiveSecondPress(gesture:)))
laterActionPress.minimumPressDuration = 1.5
someView.addGestureRecognizer(quickActionPress)
someView.addGestureRecognizer(laterActionPress)
// If 1.5 detected, only execute that one
quickActionPress.require(toFail: laterActionPress)
@objc func zeroFiveSecondPress(gesture: UIGestureRecognizer) {
// Do something
print("0.5 press")
}
@objc func oneFiveSecondPress(gesture: UIGestureRecognizer) {
zeroFiveSecondPress(gesture: gesture)
// Do something else
print("1.5 press")
}
我试过你的方法。 quickActionPress函数将启动,但laterActionPress函数从不会执行。 –
更新的工作解决方案 – nathan
如果用户持有超过1.5秒,您需要两个操作或只有更多的时间操作? –
@ReinierMelian我希望这两种行为都发生。 –