Hit Testing

    并不关心任何响应链事件,所以不能直接处理触摸事件或者手势。但是它有一系列的方法帮你处理事件:-containsPoint:-hitTest:

    -containsPoint:接受一个在本图层坐标系下的CGPoint,如果这个点在图层frame范围内就返回YES。如清单3.4所示第一章的项目的另一个合适的版本,也就是使用-containsPoint:方法来判断到底是白色还是蓝色的图层被触摸了
    (图3.10)。这需要把触摸坐标转换成每个图层坐标系下的坐标,结果很不方便。

    图3.10 点击图层被正确标识

    清单3.5 使用hitTest判断被点击的图层

    1. - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
    2. {
    3. //get touch position
    4. CGPoint point = [[touches anyObject] locationInView:self.view];
    5. //get touched layer
    6. CALayer *layer = [self.layerView.layer hitTest:point];
    7. if (layer == self.blueLayer) {
    8. [[[UIAlertView alloc] initWithTitle:@"Inside Blue Layer"
    9. message:nil
    10. delegate:nil
    11. otherButtonTitles:nil] show];
    12. [[[UIAlertView alloc] initWithTitle:@"Inside White Layer"
    13. message:nil
    14. delegate:nil
    15. cancelButtonTitle:@"OK"
    16. otherButtonTitles:nil] show];
    17. }

    注意当调用图层的-hitTest:方法时,测算的顺序严格依赖于图层树当中的图层顺序(和UIView处理事件类似)。之前提到的zPosition属性可以明显改变屏幕上图层的顺序,但不能改变事件传递的顺序。