1. User touch
2. event is created
3. hit testing by coordinates - find first responder - UIView and successors (UIWindow)
3.1 hit testing - recursive find the most deep view
3.1.1 point inside - check coordinates
4. Send Touch Event to the First Responder
类图
3 命中测试
找First Responder
First Responder 在这种情况下是最深的UIView point()(hitTest() 在内部使用point()) 方法,该方法返回true。它总是经过UIApplication -> UIWindow -> First Responder
func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView?
func point(inside point: CGPoint, with event: UIEvent?) -> Bool
内部hitTest() 看起来像
func hitTest() -> View? {
if (isUserInteractionEnabled == false || isHidden == true || alpha == 0 || point() == false) { return nil }
for subview in subviews {
if subview.hitTest() != nil {
return subview
}
}
return nil
}
4 发送触摸事件到First Responder
//UIApplication.shared.sendEvent()
//UIApplication, UIWindow
func sendEvent(_ event: UIEvent)
//UIResponder
func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?)
func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?)
func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?)
func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?)
我们来看一个例子
响应者链
这是一种chain of responsibility 模式。它由可以处理UIEvent 的UIResponser 组成。在这种情况下,它从覆盖touch... 的第一响应者开始。 super.touch... 调用响应链中的下一个链接
Responder chain 也被 addTarget 或 sendAction 使用,例如事件总线
//UIApplication.shared.sendAction()
func sendAction(_ action: Selector, to target: Any?, from sender: Any?, for event: UIEvent?) -> Bool
看例子
class AppDelegate: UIResponder, UIApplicationDelegate {
@objc
func foo() {
//this method is called using Responder Chain
print("foo") //foo
}
}
class ViewController: UIViewController {
func send() {
UIApplication.shared.sendAction(#selector(AppDelegate.foo), to: nil, from: view1, for: nil)
}
}
在处理多点触控时会考虑*isExclusiveTouch
[Android onTouch]