.Cancelled
和.Failed
状态有什么区别?
将手势识别器的状态设置为.Cancelled
或.Failed
如何影响手势识别器本身?
手势识别器的状态何时变为.Cancelled
和.Failed
?
手势识别器在哪一点标记为“已识别”?过渡到.Began
后?
是的话,手势的状态也可以设置为.Began
中的touchesMoved
吗?
例如,在哪个阶段UIPinchGestureRecognizer可以识别捏捏手势?我猜只是在touchesMoved
中,因为捏是一种连续手势。
最佳答案
实际上,.Cancelled和.Failed状态之间没有区别。两者均导致手势识别器无法处理手势。我想这只是一个命名约定。
但是,不同之处还在于两种状态如何影响手势处理。
这取决于手势识别器的先前状态。
.Possible
(触摸的.Began
阶段)中的touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent)
转换为UITouchPhase.Began
,而不是使用相同的方法转换为.Failed
或.Cancelled
,则队列中的下一个手势识别器(附加到视图)将有机会处理手势。没有动作消息将被发送。 touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent)
(触摸的UITouchPhase.Began
阶段)中从.Possible转换为.Begin,则从touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent)
方法转换为.Failed
或.Cancelled
时,手势识别将完全失败,并且将不会发生任何事情。但是无论如何都会发送动作消息。 因此,这里的视图控制器:
class ViewController: UIViewController {
func panHandler(sender: UIPanGestureRecognizer) {
print("panHandler")
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let customRecognizer = CustomGestureRecognizer(target: self, action: #selector(ViewController.customHandler(_:)))
view.addGestureRecognizer(customRecognizer)
let panRecognizer = UIPanGestureRecognizer(target: self, action: #selector(ViewController.panHandler(_:)))
view.addGestureRecognizer(panRecognizer)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func customHandler(c: CustomGestureRecognizer) {
print("customHandler")
}
}
这里是一个自定义手势识别器:
import UIKit
import UIKit.UIGestureRecognizerSubclass
class CustomGestureRecognizer: UIGestureRecognizer {
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent) {
super.touchesBegan(touches, withEvent: event)
state = .Began
if touches.count == 1 {
//state = .Failed
}
print("CustomGestureRecognizer.touchesBegan")
}
override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent) {
super.touchesMoved(touches, withEvent: event)
if state == .Failed {
return
}
if touches.count == 1 {
state = .Failed //.Cancelled
}
state = .Changed
print("CustomGestureRecognizer.touchesMoved")
}
override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent) {
super.touchesEnded(touches, withEvent: event)
state = .Ended
print("CustomGestureRecognizer.touchesEnded")
}
}
只需注释/取消注释第8、10和23行上的代码,即可看到不同之处。
关于ios - UIGestureRecognizerState.Cancelled与UIGestureRecognizerState.Failed,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/38574921/