我有一个包含UILabel的单元格的UITableView。当我点击UILabel时,我想要执行一个动作,因此我添加了一个UITapGestureRecognizer。
UILabel *telephone = (UILabel *)[cell.contentView viewWithTag:420];
telephone.userInteractionEnabled = YES;
UITapGestureRecognizer *tapToCall = [[UITapGestureRecognizer alloc] initWithTarget:telephone action:@selector(tapToCall:)];
[telephone addGestureRecognizer:tapToCall];
然后我定义了选择器方法:
-(void)tapToCall: (UITapGestureRecognizer*) sender {
UILabel *telephone = (UILabel *) sender.view;
NSLog(@"%@", telephone.text);
}
但是现在我触摸UILabel时收到错误:
2017-03-07 13:17:49.220 [37354:2794848] -[UILabel tapToCall:]: unrecognized selector sent to instance 0x7fc39f459250
2017-03-07 13:17:49.253 [37354:2794848] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[UILabel tapToCall:]: unrecognized selector sent to instance 0x7fc39f459250'
我在这里做错了什么?
答案 0 :(得分:2)
从initWithTarget:telephone
更改目标(不是针对特定控件)
UITapGestureRecognizer *tapToCall = [[UITapGestureRecognizer alloc] initWithTarget:telephone
到initWithTarget:self
(需要在当前类中调用)
UITapGestureRecognizer *tapToCall = [[UITapGestureRecognizer alloc] initWithTarget:self
完整答案
UILabel *telephone = (UILabel *)[cell.contentView viewWithTag:420];
UITapGestureRecognizer *tapToCall = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapToCall:)];
telephone.userInteractionEnabled = YES;
[telephone addGestureRecognizer:tapToCall];
答案 1 :(得分:1)
像这样改变
UITapGestureRecognizer *tapToCall = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapToCall:)];
[telephone addGestureRecognizer:tapToCall];
答案 2 :(得分:0)
应该是这样的
UILabel *telephone = (UILabel *)[cell.contentView viewWithTag:420];
UITapGestureRecognizer *tapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTap:)];
[tapRecognizer setDelegate:self];
[tapRecognizer setNumberOfTapsRequired:1];
[telephone addGestureRecognizer:tapRecognizer];
- (void)handleTap: (UITapGestureRecognizer*) sender {
UILabel *telephone = (UILabel *) sender.view;
NSLog(@"%@", telephone.text);
NSLog(@"%ld", (long)telephone.tag);
switch(telephone.tag) {
case 0: { }
break;
case 1: { }
break;
}
}