我正在使用一个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];
}
发布于 2013-07-24 17:32:02
UITapGestureRecognizer *recognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction)];
[recognizer setNumberOfTapsRequired:1];
lblName.userInteractionEnabled = YES;
[lblName addGestureRecognizer:recognizer];
发布于 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的情况下也是如此
发布于 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)")
}
https://stackoverflow.com/questions/10079019
复制相似问题