Objective-c UITapGestureRecognizer 无法识别的选择器
Posted
技术标签:
【中文标题】Objective-c UITapGestureRecognizer 无法识别的选择器【英文标题】:Objective-c UITapGestureRecognizer unrecognized selector 【发布时间】:2017-03-07 12:22:44 【问题描述】:我有一个包含 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'
我在这里做错了什么?
【问题讨论】:
【参考方案1】:从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];
【讨论】:
【参考方案2】:这样改
UITapGestureRecognizer *tapToCall = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapToCall:)];
[telephone addGestureRecognizer:tapToCall];
【讨论】:
【参考方案3】:应该是这样的
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;
【讨论】:
以上是关于Objective-c UITapGestureRecognizer 无法识别的选择器的主要内容,如果未能解决你的问题,请参考以下文章
如何关闭 UIPopoverController 并选择表格单元格?