简体   繁体   English

如何将 UITapGestureRecognizer 添加到表视图单元格内的 UILabel?

[英]How can I add a UITapGestureRecognizer to a UILabel inside a table view cell?

I am using a NIB file to layout a custom table view cell.我正在使用 NIB 文件来布局自定义表格视图单元格。 This cell has a label with outlet called lblName.这个单元格有一个 label,出口名为 lblName。 Adding a UITapGestureRecognizer to this label never fires the associated event.将 UITapGestureRecognizer 添加到此 label 永远不会触发关联的事件。 I have userInteractionEnabled = YES.我有 userInteractionEnabled = YES。

I'm guessing that the problem is that the UILabel is in a TableView and that the table/cell view is intercepting the taps.我猜问题是 UILabel 在 TableView 中并且表/单元格视图正在拦截水龙头。 Can I do something about this?我能做点什么吗?

All I want to do is perform some custom action when a UILabel is pressed.我想要做的就是在按下 UILabel 时执行一些自定义操作。 All of the solutions for doing this that I've seen are ridiculous.我见过的所有这样做的解决方案都是荒谬的。 It should be easy using the standard tool set.使用标准工具集应该很容易。 But evidently not.但显然不是。

Here's the code I'm using:这是我正在使用的代码:

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

EASY WAY:简单的方法:

You may also use a invisible button on the top of that label. So it will reduce your work of adding tapGesture for that label.你也可以在那个 label 的顶部使用一个不可见的按钮。这样它会减少你为那个 label 添加 tapGesture 的工作。

ALTERNATIVE WAY:替代方式:

You should not create an IBOutlet for that UILabel .您不应为该UILabel创建 IBOutlet。 When you do that,you will add a outlet in custom class implementation file.当你这样做时,你将在自定义 class 实现文件中添加一个插座。 You cannot access in other file.您无法访问其他文件。 So set a tag for that label in custom class IB and write a code in cellForRowAtIndexPath: method.因此,在自定义 class IB中为该 label 设置一个标签,并在cellForRowAtIndexPath:方法中编写代码。

UPDATED:更新:

In cellForRowAtIndexPath: method,cellForRowAtIndexPath:方法中,

for(UIView *view in cell.contentViews.subviews) {
    if(view.tag == 1) {
        UITapGestureRecognizer *tap=[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction)];
        [tap setNumberOfTapsRequired:1];
        [view addGestureRecognizer:tap];
    }
}
UITapGestureRecognizer *recognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction)]; 
[recognizer setNumberOfTapsRequired:1];
lblName.userInteractionEnabled = YES;  
[lblName addGestureRecognizer:recognizer];

Doing this works without problems:这样做没有问题:

- (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;
      ....
     }
}

even in the case in which creates the UILabel with IB即使在使用 IB 创建 UILabel 的情况下

You can use below code to add tap gesture on UILable in UITableView cell您可以使用以下代码在 UITableView 单元格中的 UILable 上添加点击手势

UITapGestureRecognizer *tapGeature = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(lblClick:)];
tapGeature.delegate =self;
tapGeature.numberOfTapsRequired = 1;

cell.lbl.userInteractionEnabled = YES;
[cell.lbl addGestureRecognizer:tapGeature];

and to access the selector method并访问选择器方法

- (void)lblClick:(UITapGestureRecognizer *)tapGesture {
    UILabel *label = (UILabel *)tapGesture.view;
    NSLog(@"Lable tag is ::%ld",(long)label.tag);
}

For Swift Swift

let tapGesture : UITapGestureRecognizer = UITapGestureRecognizer.init(target: self, action: #selector(lblClick(tapGesture:)))
tapGesture.delegate = self
tapGesture.numberOfTapsRequired = 1
cell.lbl.userInteractionEnabled = true
cell.lbl.tag = indexPath.row
cell.lbl.addGestureRecognizer(tapGesture)

func lblClick(tapGesture:UITapGestureRecognizer){
   print("Lable tag is:\(tapGesture.view!.tag)")
}

Update for 2019 with Swift 5, based upon Hardik Thakkar's solution. 2019 年更新为 Swift 5,基于 Hardik Thakkar 的解决方案。 To detect taps on a UIlabel in a cell, find the cellForRowAt method in your view controller below.要检测单元格中 UIlabel 上的点击,请在下面的视图 controller 中找到 cellForRowAt 方法。

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

Place the following code in to the method above before returning the cell:在返回单元格之前将以下代码放入上面的方法中:

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

Add a method to your view controller to handle the taps:添加一个方法到您的视图 controller 来处理水龙头:

@objc func labelTap(tapGesture:UITapGestureRecognizer){
    print("Label tag is:\(tapGesture.view!.tag)")
}

You can add next in your cell's -awakeFromNib method您可以在单元格的 -awakeFromNib 方法中添加 next

UITapGestureRecognizer* gesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapGestureRecognizerAction:)];
[self.yourLabel setUserInteractionEnabled:YES];
[self.yourLabel addGestureRecognizer:gesture];

Once you assign the tap gesture to the UILabel and set the user interaction to enabled, in your callback function you can find the indexpath from the cell view but searching through the nest of superviews:将点击手势分配给 UILabel 并将用户交互设置为启用后,在回调 function 中,您可以从单元格视图中找到索引路径,但可以搜索超级视图的嵌套:

- (UITableViewCell *) findCellInSuperview:(UIView *)view
{
UITableViewCell *cell = nil;

    NSString *className = NSStringFromClass([[view superview] class]);
    if ([className isEqualToString:@"UITableViewCell"]) {
        cell = (UITableViewCell *)[view superview];
    } else {
        if ([view superview] != nil) {
            cell = [self findCellInSuperview:[view superview]];
        }
    }

return cell;
}

For Swift 3对于 Swift 3

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

And then接着

func lblClick(tapGesture:UITapGestureRecognizer){
    print("Lable tag is:\(tapGesture.view!.tag)")
}

The way Dinesh suggested will work without the for loop using the property variable. Dinesh 建议的方式将在没有使用属性变量的 for 循环的情况下工作。

UITapGestureRecognizer *tap=[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction)];
[tap setNumberOfTapsRequired:1];
[self.myUILabel addGestureRecognizer:tap];

For Swift, you can add this inside your cellForRowAtIndexPath method.对于 Swift,您可以将其添加到您的 cellForRowAtIndexPath 方法中。

var tap = UITapGestureRecognizer(target: self, action: "labelTapped")
tap.numberOfTapsRequired = 1
cell.label.addGestureRecognizer(tap)
cell.label.tag = indexPath.row

Then for action然后行动

func labelTapped(gesture: UITapGestureRecognizer) {
    let indexPath = NSIndexPath(forRow: gesture.view!.tag, inSection: 0)
    let cell = tableView.cellForRowAtIndexPath(indexPath) as UITableViewCell

    // Do whatever you want.
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在自定义表格视图单元格上获取UILabel? - How can I get UILabel on a custom table view cell? 如何在点击UILabel(UITapGestureRecognizer)时重新加载表格视图数据 - how to reload the Table view data when tap on UILabel(UITapGestureRecognizer) 当UITapGestureRecognizer在prepareForSegue中点击并捕获其中的UIImage时,如何获取自定义表格视图单元格的索引路径 - How to get the indexpath of a custom table view cell when an UIImage inside of it is tapped and captured by UITapGestureRecognizer in prepareForSegue 将 UILabel 中的文本放在表视图单元格内 - Fitting text in UILabel inside a Table View Cell 如何将联系人姓名添加到表视图单元格? - How can I add the name of a contact to my table view cell? 如何将UITapGestureRecognizer添加到presentViewController并查看 - how to add UITapGestureRecognizer to presentViewController and to view 如何在 UILabel 内的文本中添加一些插图? - How can I add some insets to the text inside the UILabel? 如何在iOS中将表格视图中的表格单元格中的图像解析为详细信息视图? - How can I parse image from table cell inside table view to detail view in iOS? 如何使用Swift在UICollection View单元内添加表视图? - How do i add a Table View inside a UICollection View Cell Using Swift? 我如何单击UI表格视图单元格(自定义单元格)内的按钮,然后转到其他ViewController - how can I click button inside UI table view cell (custom cell ) and then goto other viewcontroller
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM