OGeek|极客世界-中国程序员成长平台

标题: ios - 如何通过 -addSublayer : respond to touch events? 添加 UI 元素 [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-13 09:45
标题: ios - 如何通过 -addSublayer : respond to touch events? 添加 UI 元素

以下是我用来通过 -addSublayer 将 UIButton 添加到层的代码:

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 actionselector(XbuttonTouchEvent)    
forControlEvents:UIControlEventTouchUpInside];

[tile addSublayer:XImageButton.layer]; 

XImageButton 没有响应触摸事件。我该如何解决这个问题,以便它做出响应?



Best Answer-推荐答案


你不能。您必须将按钮添加为 subview 。

UIKit 触摸事件转发是 UIResponder 的一项功能,CALayers 不继承自 UIResponder,所以除非你想从第一原理实现触摸处理,否则这不是可行的方法。

要将渐变层转换为 View ,有两种选择:

1) 创建一个新的 UIView 子类并重写它的 +(Class)layerClass 方法返回 CAGradientLayer。

2) 创建一个常规 UIView 并将您的 CAGradientLayer 添加为子层,然后将您的按钮添加为 View 的 subview ,而不是将其直接添加到 CAGradientLayer。

关于ios - 如何通过 -addSublayer : respond to touch events? 添加 UI 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8110543/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://sqlite.in/) Powered by Discuz! X3.4