【问题标题】:trying to add a UITapGestureRecognizer but not working尝试添加 UITapGestureRecognizer 但不工作
【发布时间】:2014-02-20 20:44:02
【问题描述】:

我尝试在 UILabel 上设置一个简单的 UITapGestureRecognizer,但它不起作用。似乎什么都没有被识别,也没有任何东西写入日志。

在从 viewDidLoad 调用的方法中

  UILabel *miTN = [[UILabel alloc] initWithFrame:CGRectMake(300, 100, 150, 15)];
  [miTN setUserInteractionEnabled:YES];
  UITapGestureRecognizer *tapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapRecognized)];
  [miTN addGestureRecognizer: tapRecognizer];
  [miView addSubview:miTN];

   ... later

  - (void)tapRecognized:(id)sender
  {
    NSLog(@"that tap was recognized");
  }

此外,这是为了响应异步网络调用而调用的。这会导致问题吗?是否还有其他可能导致问题的问题?我不太确定调试的第一步是什么 - 我检查了颜色混合图层以查看它们是否重叠但似乎没有。

【问题讨论】:

  • miView 是什么类型的视图?你看到屏幕上的景色了吗?如果它是纵向的 iPhone,则它的原点从屏幕右侧水平对齐 20 像素。
  • 这只是一个 UIView - 一个可能的问题是此代码存在于回调块中,但我认为它应该正确保留。标签在模拟器中写得很好。
  • 是否添加了其他手势或任何父视图?
  • 我不这么认为——我现在正在调查。我最初认为这只是我的一些愚蠢的语法错误,但现在认为这是某种意料之外的交互。

标签: ios ios7 uitapgesturerecognizer


【解决方案1】:

您应该将 UIGestureRecognizerDelegate 添加到您的视图控制器类的协议列表中

@interface TSViewController : UIViewController <UIGestureRecognizerDelegate>

并插入字符串:

tapRecognizer.delegate = self;

替换

UITapGestureRecognizer *tapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapRecognized)];

UITapGestureRecognizer *tapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapRecognized:)];

【讨论】:

  • 你确定有必要吗? OP 没有使用任何委托方法。
  • 你可以试试。我确定。
  • @sooper 关于委托,您可以阅读stackoverflow.com/questions/11355671/…
  • 当您为操作设置目标 (self) 时,它仍然可以在不设置委托和实现协议的情况下工作。阅读为解决您所链接的问题而发布的最后一条评论。
【解决方案2】:

在 Swift 中,您必须按如下方式启用。
yourLabel.isUserInteractionEnabled = true

【讨论】:

    猜你喜欢
    • 2014-03-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-01
    相关资源
    最近更新 更多