【问题标题】:How can I make a UI element added via -addSublayer: respond to touch events?如何通过 -addSublayer 添加 UI 元素:响应触摸事件?
【发布时间】:2011-11-13 08:41:55
【问题描述】:

以下是我用来通过-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 action:@selector(XbuttonTouchEvent)    
forControlEvents:UIControlEventTouchUpInside];

[tile addSublayer:XImageButton.layer]; 

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

【问题讨论】:

    标签: ios cocoa-touch uibutton core-animation


    【解决方案1】:

    你不能。您必须将按钮添加为子视图。

    UIKit 触摸事件转发是 UIResponder 的一个特性,并且 CALayers 不从 UIResponder 继承,所以除非你想从第一原理实现触摸处理,否则这不是要走的路。

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

    1) 创建一个新的 UIView 子类并覆盖其+(Class)layerClass 方法以返回 CAGradientLayer。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-07
      • 2011-01-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多