HitTest on CALayer - how do you find which actual layer was hit?

Situation: You need to find which layer the user touched.

Problem: Apple says that we should use [CALayer presentationLayer] to perform impact testing so that it displays what is actually on the screen at that time (it captures mid-animation information, etc.).

... except: presentationLayer does NOT return the original layers, it returns copies of it ... like this: hitTest will return a new CALayer instance that is not equivalent to the original.

How to find which actual CALayer was hit?

eg.

CALayer* x = [CALayer layer]; CALayer* y = [CALayer layer]; [self.view.layer addSublayer: x]; [self.view.layer addSublayer: y]; ... CALayer* touchedLayer = [self.view.layer.presentationLayer hitTest:touchPoint]; 

... but touched Layer "x", or is it "y"?

 if( touchedLayer == x ) // this won't work, because touchedLayer is - by definition from Apple - a new object 
+4
source share
2 answers

Oh! I just figured it out by reading the newsletter for another issue with CALayer.

After calling [CALayer presentationLayer] and working with the "presentation clone" of the tree layer, you can take any object in this tree and call [CALayer modelLayer] on it to return the original reference object to the same position in the original tree.

This link is stable (verified - it works).

Apple's docs are a bit ... obscure ... on that. And they imply that this "sometimes" fails (" ... the results are undefined ") - but for me it is good enough.

+2
source

Adam's answer is correct and helped me. Here the code I used can help someone else.

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

Source: https://habr.com/ru/post/1382917/


All Articles