Search code examples
ioscocoa-touchuibuttoncore-animation

How can I make a UI element added via -addSublayer: respond to touch events?


The following is code that I use to add a UIButton to a layer via -addSublayer:

CAGradientLayer * tile = [[tile alloc] init];      

UIButton *XImageButton = [[UIButton alloc]init];
 XImageButton.frame= CGRectMake(kXButtonlocX, kXButtonlocY, kXButtonHeight,kXButtonWidth );

[XImageButton setTitle:@"xbutton" forState:UIControlStateNormal];
[XImageButton addTarget:nil action:@selector(XbuttonTouchEvent)    
forControlEvents:UIControlEventTouchUpInside];

[tile addSublayer:XImageButton.layer]; 

The XImageButton isn't responding to touch events. How can I fix this so that it does respond?


Solution

  • You can't. You'll have to add the button as a subview instead.

    UIKit touch event forwarding is a feature of UIResponder, and CALayers don't inherit from UIResponder, so unless you fancy implementing touch handling from first principles this is not the way to go.

    To convert your gradient layer to a view, there are two options:

    1) Create a new UIView subclass and override its +(Class)layerClass method to return CAGradientLayer.

    2) Create a regular UIView and add your CAGradientLayer as a sublayer, then add your button as a subview of the view instead of adding it to the CAGradientLayer directly.