首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何向表格视图单元格内的UILabel添加UITapGestureRecognizer?

如何向表格视图单元格内的UILabel添加UITapGestureRecognizer?
EN

Stack Overflow用户
提问于 2012-04-10 03:59:23
回答 8查看 39.2K关注 0票数 23

我正在使用一个NIB文件来布局一个自定义的表格视图单元。此单元格有一个带有outlet的标签,名为lblName。向此标签添加UITapGestureRecognizer永远不会触发关联的事件。我的userInteractionEnabled = YES。

我猜测问题在于UILabel位于TableView中,而表/单元格视图正在拦截这些分流。我能为此做点什么吗?

我所要做的就是在按下UILabel时执行一些自定义操作!我所见过的所有解决方案都是荒谬的。使用标准工具集应该很容易。但显然不是。

下面是我使用的代码:

- (void)tapAction {
    NSLog(@"Tap action");
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib

    UITapGestureRecognizer *recognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction)]; 
    [recognizer setNumberOfTapsRequired:1];
    //lblName.userInteractionEnabled = true;  (setting this in Interface Builder)
    [lblName addGestureRecognizer:recognizer];
}
EN

回答 8

Stack Overflow用户

发布于 2013-07-24 17:32:02

UITapGestureRecognizer *recognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction)]; 
[recognizer setNumberOfTapsRequired:1];
lblName.userInteractionEnabled = YES;  
[lblName addGestureRecognizer:recognizer];
票数 14
EN

Stack Overflow用户

发布于 2012-04-10 04:16:08

这样做是没有问题的:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{
   ...
   // create you cell
   UILabel *lbl = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 100, 50)];
   [lbl setText:@"example"];
   [lbl setUserInteractionEnabled:YES];
   [cell.contentView addSubview:lbl];
   UITapGestureRecognizer *tap=[[UITapGestureRecognizer alloc] initWithTarget:self    action:@selector(tapAction:)];
   tap.tag = [NSIndexPath row];
   [tap setNumberOfTapsRequired:1];
   [lbl addGestureRecognizer:tap];
   ... 
}

- (void)tapAction:(id)sender {
  switch(((UITapGestureRecognizer *)sender).view.tag) {
     case 0:
          // code
          break;
     case 1:
         // code
         break;
      ....
     }
}

即使在使用IB创建UILabel的情况下也是如此

票数 10
EN

Stack Overflow用户

发布于 2019-12-11 17:27:56

基于Hardik Thakkar解决方案的Swift 5 2019年更新。要检测单元格中UIlabel上的点击,请在下面的视图控制器中找到cellForRowAt方法。

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {}

在返回单元格之前,将以下代码放入上述方法中:

let tapGesture : UITapGestureRecognizer = UITapGestureRecognizer.init(target: self, action: #selector(labelTap(tapGesture:)))
tapGesture.delegate = self
tapGesture.numberOfTapsRequired = 1
cell.yourLabel.isUserInteractionEnabled = true
cell.yourLabel.tag = indexPath.row
cell.yourLabel.addGestureRecognizer(tapGesture)            
return cell

将一个方法添加到视图控制器以处理点击:

@objc func labelTap(tapGesture:UITapGestureRecognizer){
    print("Label tag is:\(tapGesture.view!.tag)")
}
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/10079019

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档