如何通过-addSublayer添加UI元素:响应触摸事件? [英] How can I make a UI element added via -addSublayer: respond to touch events?

查看:185
本文介绍了如何通过-addSublayer添加UI元素:响应触摸事件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是我用于通过 -addSublayer 向图层添加UIButton的代码:

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]; 

XImageButton 事件。

推荐答案

你不能。

UIKit触摸事件转发是UIResponder的一个功能,而CALayers不会从UIResponder继承,所以除非你

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)创建一个新的UIView子类并覆盖它的 +(Class)layerClass 方法返回CAGradientLayer。

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

2)创建一个常规的UIView并添加您的CAGradientLayer作为子图层,然后添加您的按钮作为视图的子视图,而不是直接添加到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.

这篇关于如何通过-addSublayer添加UI元素:响应触摸事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆