简体   繁体   中英

How can I make a CALayer clickable?

I am using CATransformLayer to create a bunch of layers and animate them with 3D perspective to make a cube (something like this)

带子层的CATransformLayer

What's the best way of adding a UIButton to one of the sides to this cube? I would like to be able receive events and access the buttom from an IBOutlet.

I've tried creating a UIView with a button inside it into my XIB and inserting its layer into the CATransformLayer, it shows up but the button isn't clickable. I have a feeling this is because UIKit deals with the Touch/events side of things, the layers are just there to do the drawing.

(btw, I have seen this question , but feel this case is different enough to warrant a new post)

the root view thats hosting all the layers is getting all touches for the layer tree

in there you gotta do

CALayer *touchedLayer = [self.rootLayer hitTest:touches.anyObject.locationInWindow];

from the comment: if you want to check during animations assk your presentation layer:

CALayer *touchedLayer = [self.rootLayer.presentationLayer hitTest:touches.anyObject.locationInWindow];

Thanks to Daij for the hint, here's my solution - would appreciated any comments/improvements

- (IBAction)viewTapped:(UITapGestureRecognizer *)sender
{
    CGPoint location = [sender locationInView:sender.view];
    CALayer *layer = [sender.view.layer hitTest:location];

    BOOL contains = [self.btnPlay.layer.sublayers containsObject:layer];
    if(contains)
    {
        [self.btnPlay sendActionsForControlEvents:UIControlEventTouchUpInside];

    }


}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM