如何在表格视图单元格中的UILabel中添加UITapGestureRecognizer? [英] How can I add a UITapGestureRecognizer to a UILabel inside a table view cell?
问题描述
我正在使用NIB文件来布局自定义表格视图单元格。这个单元格有一个带有出口的标签,名为lblName。将UITapGestureRecognizer添加到此标签永远不会触发关联的事件。我有userInteractionEnabled = YES。
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.
我猜测问题是UILabel在TableView中并且表/单元视图拦截了水龙头。我可以对此做些什么吗?
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时执行一些自定义操作!我所见过的所有解决方案都是荒谬的。使用标准工具集应该很容易。但显然不是。
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.
这是我正在使用的代码:
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];
}
推荐答案
方便:
您也可以使用该标签顶部的隐藏按钮。因此,它将减少为该标签添加tapGesture的工作。
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.
替代方式:
您不应为此<$创建IBOutlet C $ C>的UILabel 。执行此操作时,您将在自定义类实现文件中添加插座。您无法访问其他文件。因此,在自定义类 IB
中为该标签设置标记,并在 cellForRowAtIndexPath:
方法中编写代码。
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 IB
and write a code 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];
}
}
这篇关于如何在表格视图单元格中的UILabel中添加UITapGestureRecognizer?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!