How can I make a UI element added via -addSublayer

2019-05-26 20:06发布

问题:

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?

回答1:

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.