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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10079019/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 17:47:06  来源:igfitidea点击:

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

iosuitapgesturerecognizer

提问by Bryan

I am using a NIB file to layout a custom table view cell. This cell has a label with outlet called lblName. Adding a UITapGestureRecognizer to this label never fires the associated event. I have userInteractionEnabled = YES.

我正在使用 NIB 文件来布局自定义表格视图单元格。该单元格有一个带有出口的标签,名为 lblName。添加一个 UITapGestureRecognizer 到这个标签永远不会触发相关的事件。我有 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. Can I do something about this?

我猜问题是 UILabel 在 TableView 中,并且表格/单元格视图正在拦截水龙头。我可以做些什么吗?

All I want to do is perform some custom action when a UILabel is pressed! 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.

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

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

采纳答案by Dinesh Raja

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.

您也可以使用该标签顶部的隐形按钮。因此,它将减少您为该标签添加 tapGesture 的工作。

ALTERNATIVE WAY:

替代方式:

You should not create an IBOutlet for that UILabel. When you do that,you will add a outlet in custom class implementation file. You cannot access in other file. So set a tag for that label in custom class IBand write a code in cellForRowAtIndexPath:method.

您不应为此创建 IBOutlet UILabel。当您这样做时,您将在自定义类实现文件中添加一个插座。您无法在其他文件中访问。因此,在自定义类中为该标签设置一个标签,IB并在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];
    }
}

回答by sarit bahuguna

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

回答by WhiteTiger

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 的情况下

回答by Hardik Thakkar

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

对于斯威夫特

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)")
}

回答by mobileappz

Update for 2019 with Swift 5, based upon Hardik Thakkar's solution. To detect taps on a UIlabel in a cell, find the cellForRowAt method in your view controller below.

使用 Swift 5 更新 2019 年,基于 Hardik Thakkar 的解决方案。要检测单元格中 UIlabel 的点击,请在下面的视图控制器中找到 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:

添加一个方法到你的视图控制器来处理点击:

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

回答by fegoulart

For Swift 3

对于斯威夫特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)")
}

回答by landonandrey

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

回答by adjwilli

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 并将用户交互设置为启用,在您的回调函数中,您可以从单元格视图中找到索引路径,但会搜索超级视图的嵌套:

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

回答by Leo Chan

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

回答by Andrespch

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