先看看apple references对hitTest的说明:
Returns the farthest descendant of the receiver in the view hierarchy (including itself) that contains a specified point.
Declaration
SWIFT
func hitTest(_ point: CGPoint,
withEvent event: UIEvent?) -> UIView?
OBJECTIVE-C
- (UIView *)hitTest:(CGPoint)point
withEvent:(UIEvent *)event
Parameters
point
A point specified in the receiver’s local coordinate system (bounds).
event
The event that warranted a call to this method. If you are calling this method from outside your event-handling code, you may specify nil.
Return Value
The view object that is the farthest descendent the current view and contains point. Returns nil if the point lies completely outside the receiver’s view hierarchy.
Discussion
This method traverses the view hierarchy by calling the pointInside:withEvent: method of each subview to determine which subview should receive a touch event. If pointInside:withEvent: returns YES, then the subview’s hierarchy is similarly traversed until the frontmost view containing the specified point is found. If a view does not contain the point, its branch of the view hierarchy is ignored. You rarely need to call this method yourself, but you might override it to hide touch events from subviews.
This method ignores view objects that are hidden, that have disabled user interactions, or have an alpha level less than 0.01. This method does not take the view’s content into account when determining a hit. Thus, a view can still be returned even if the specified point is in a transparent portion of that view’s content.
Points that lie outside the receiver’s bounds are never reported as hits, even if they actually lie within one of the receiver’s subviews. This can occur if the current view’s clipsToBounds property is set to NO and the affected subview extends beyond the view’s bounds.
如果你需要屏蔽子view,则可以重写该函数,返回当前view即可。
举个例子:假设当前的事件链是这样(rootViewController—根view—Scrollview—ImageView)
情况一:Imageview不处理手势或touch处理,则事件会在scrollview处理
情况二:Imageview增加手势等处理,则事件不会停留在scrollview,会在imageview这处理。
关于事件链的组织,可以参考:
iOS的事件分发,摘录部分:
iOS中的事件有3类,触摸事件(单点,多点,手势)、传感器事件(加速度传感器)和远程控制事件,这里我介绍的是第一种事件的分发处理。
上面的这张图来自苹果的官方。描述了Responder的链,同时也是事件处理的顺序。通过这两张图,我们可以发现:
1. 事件顺着responder chain传递,如果一环不处理,则传递到下一环,如果都没有处理,最后回到UIApplication(UIApplication的nextresponder是APPdelete),再不处理就会抛弃
2. view的下一级是包含它的viewController,如果没有viewController则是它的superView
3. viewController的下一级是它的view的superView
4. view之后是window,最后传给application,这点iOS会比OS X简单(application就一个,window也一个)
一系列的UIEvent。
1,每次传递其中有一个,他会从事件链的最前面开始传递,先讲event传递给事件链顶部的View的手势们。然后看有没有识别的,如果没有就继续到下一个响应者的手势们,如果立即识别,那么就停止传递。如果传递了整个链,还没有发现有识别的,怎么办呢。别以为事件就丢掉了,事件会从回到链的最前端,然后开始找第一个实现touch(touchbegin,touchend,等等)的view进行识别,然后停止本次传递。
2.从时间中再取出一个,继续进行一过程。最终到没有事件位置。