.Cancelled
和 .Failed
状态有什么区别?
将手势识别器的状态设置为.Cancelled
或.Failed
对手势识别器本身有何影响?
手势识别器的状态何时变为.Cancelled
和.Failed
?
手势识别器在什么时候被标记为“已识别”?在过渡到 .Began
之后?
当是时,手势的状态是否也可以在 touchesMoved
中设置为 .Began
?
例如,UIPinchGestureRecognizer 在哪个阶段识别捏合手势?我猜只在 touchesMoved
中,因为捏合是一种连续手势。
最佳答案
实际上.Cancelled 和.Failed 状态之间没有区别。两者都导致手势识别器无法处理手势。我想这只是一个命名约定。
不过,区别还在于两种状态如何影响手势处理。
这取决于手势识别器之前的状态。
- 如果手势识别器从
.Possible
转换而来至.Began
在touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent)
(UITouchPhase.Began
触摸阶段),比用同样的方法.Failed
或.Cancelled
,队列中的下一个手势识别器(附加到 View )将有机会处理该手势。不会发送任何操作消息。 - 但是如果手势识别器从 .Possible 转换为 .Began in
touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent)
(UITouchPhase.Began
触摸阶段),比在touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent)
.Failed
的方法或.Cancelled
手势识别只会失败,什么也不会发生。但无论如何都会发送操作消息。 - 如果注释掉第 8 行的代码,则手势识别将失败,下一个附加到 View 的手势识别器将有机会处理该手势。
所以这里是 View Controller :
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/