objective-ccocoacalayercabasicanimation

How to detect which CALayer was clicked on?


I'm having a problem detecting which CALayer is being clicked on, as these CALayers have a constant CABasicAnimation moving the x and y positions.

My current code is as follows:

-(void)mouseUp:(NSEvent *)theEvent
{
    CGPoint pointInView = NSPointToCGPoint([self convertPoint:[theEvent locationInWindow]fromView:nil]);
    CALayer* clickedOn = [(CALayer*) self.layer hitTest:[self.layer convertPoint:pointInView toLayer:self.layer.superlayer]];
    int selectedContact = -1;
    for (int i = 0; i < [contactLayers count]; i++) {
        CALayer* presentationLayer = [contactLayers[i] presentationLayer];
        if (presentationLayer == clickedOn) {
            selectedContact = i;
            break;
        }
    }
    
    if(selectedContact == -1)
        return; //no contact selected;
    
    CALayer* selectedContactLayer = contactLayers[selectedContact];
    [selectedContactLayer removeFromSuperlayer];
}

contactLayers is an NSMutableArray containing all the possible CALayers the user can click on.

Every time this runs, i always seems to end up staying -1. I'm using presentationLayer since the CALayers have a CABasicAnimation applied to them. I also tried modelLayer, but this only works if you click on the initial location of each layer.

So just a recap: I have an NSMutableArray of CALayers that all have a CABasicAnimation applied, this array is called contactLayers. When the user clicks on a layer, I need to know what layer they clicked on by setting the index to the appropriate value in the array.


Solution

  • Compute 'clickedOn' by hit testing 'self.layer.presentationLayer', not 'self.layer'