2013-05-04 95 views
1

我在这2个CALayers添加[self.layer addSublayer:subLayerA]; //...给予以下视图层次一个UIView:为什么我在UIView的则hitTest未识别的CALayer感动

UIView subclass 
- backing layer (provided by UIView) 
    - subLayerA 
    - subLayerB 

如果我在视图控制器覆盖touchesBegan那正确地提出了UIView它标识CALayer的感动:

// in view controller 

#import <QuartzCore/QuartzCore.h> 
//..... 

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { 
     UITouch *touch = [touches anyObject]; 
     CGPoint touchPoint = [touch locationInView:self.view]; 
     CALayer *touchedLayer = [self.view.layer.presentationLayer hitTest:touchPoint]; // returns a copy of touchedLayer 
     CALayer *actualLayer = [touchedLayer modelLayer]; // returns the actual CALayer touched 
     NSLog (@"touchPoint: %@", NSStringFromCGPoint(touchPoint)); 
     NSLog (@"touchedLayer: %@", touchedLayer); 
     NSLog (@"actualLayer: %@", actualLayer); 
} 

然而,如果我在的UIView,其底层是两个子层的父覆盖touchesBegan,它将返回null的CALayer的(虽然提供了正确的接触点):

// in UIView subclass 

#import <QuartzCore/QuartzCore.h> 
//..... 

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { 
    UITouch *touch = [touches anyObject]; 
    CGPoint touchPoint = [touch locationInView:self]; 
    CALayer *touchedLayer = [self.layer.presentationLayer hitTest:touchPoint]; // returns a copy of touchedLayer 
    CALayer *actualLayer = [touchedLayer modelLayer]; // returns the actual CALayer touched 
    NSLog (@"touchPoint: %@", NSStringFromCGPoint(touchPoint)); 
    NSLog (@"touchedLayer: %@", touchedLayer); 
    NSLog (@"actualLayer: %@", actualLayer); 
} 

任何想法我哪里错了?

回答

0

我仍然不确定为什么我在UIView子类中的原始代码不工作。作为一种解决方法,我可以在每个感兴趣的层上单独测试hitView。

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { 
    UITouch *touch = [touches anyObject]; 
    CGPoint touchPoint = [touch locationInView:self]; 

    //check if subLayerA touched 
    if ([subLayerA hitTest:touchPoint]) { 
     // if not nil, then subLayerA hit 
     NSLog(@"subLayerA hit"); 
    } 
    //check if subLayerB touched 
    if ([self.subLayerB hitTest:touchPoint]) { 
     // if not nil, then subLayerB hit 
     NSLog(@"subLayerB hit"); 
} 

我不会记住这是正确的呢,因为我在技术上还没有回答为什么我的原代码没有工作 - 有人还可能有答案。

1

我有这个同样的问题..

的CALayer的则hitTest方法需要在接收器的超层的坐标位置。

所以将下面的行应该修复它: 接触点= [self.layer convertPoint:接触点toLayer:self.layer.superlayer]

这可以解释为什么测试[subLayerA则hitTest:接触点]作品(接触点是在“self”的坐标空间中,它是subLayerA的父级)

希望有所帮助。

参见:https://developer.apple.com/library/ios/documentation/GraphicsImaging/Reference/CALayer_class/Introduction/Introduction.html#//apple_ref/occ/instm/CALayer/hitTest

+0

这是一个没有道理,总是有道理的。 A +。如果可以的话,我会给你买一瓶啤酒。 – 2015-07-14 18:34:23

相关问题