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

坚强是说给别人听的谎言 提交于 2019-12-08 03:06:32

问题


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.



来源:https://stackoverflow.com/questions/8110543/how-can-i-make-a-ui-element-added-via-addsublayer-respond-to-touch-events

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!