搜索
您的当前位置:首页正文

事件响应机制

来源:知库网

iOS系统检测到手指触摸(Touch)操作时会将其放入当前活动Application的事件队列,UIApplication会从事件队列中取出触摸事件并传递给key window(当前接收用户事件的窗口)处理,window对象首先会使用hitTest:withEvent:方法寻找此次Touch操作初始点所在的视图(View),即需要将触摸事件传递给其处理的视图,称之为hit-test view。

window对象会首先在view hierarchy的顶级view上调用hitTest:withEvent:,此方法会在视图层级结构中的每个视图上调用pointInside:withEvent:,如果pointInside:withEvent:返回YES,则继续逐级调用,直到找到touch操作发生的位置,这个视图也就是hit-test view。
hitTest:withEvent:方法的处理流程如下:

1. 首先调用当前视图的pointInside:withEvent:方法判断触摸点是否在当前视图内;
2. 若返回NO,则hitTest:withEvent:返回nil;
3. 若返回YES,则向当前视图的所有子视图(subviews)发送hitTest:withEvent:消息,所有子视图的遍历顺序是从top到bottom,即从subviews数组的末尾向前遍历,直到有子视图返回非空对象或者全部子视图遍历完毕;
4. 若第一次有子视图返回非空对象,则hitTest:withEvent:方法返回此对象,处理结束;
5. 若所有子视图都返回空,则hitTest:withEvent:方法返回自身(self)。

The hitTest:withEvent: method returns the hit test view for a given CGPoint and UIEvent. The hitTest:withEvent: method begins by calling the pointInside:withEvent: method on itself. If the point passed into hitTest:withEvent: is inside the bounds of the view, pointInside:withEvent: returns YES. Then, the method recursively calls hitTest:withEvent: on every subview that returns YES.

- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event {
    //根据触摸点和事件返回view
}
- (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event {
    //如果触摸点在当前view,则返回yes
}

Top