2017-03-07 17 views
-1

我有一個包含UILabel的單元格的UITableView。當我點擊UILabel時,我想要執行一個動作,因此我添加了一個UITapGestureRecognizer。Objective-c 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'

我是怎麼在這裏做錯了嗎?

回答

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

像這樣改變

UITapGestureRecognizer *tapToCall = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapToCall:)]; 
[telephone addGestureRecognizer:tapToCall]; 
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; 
    } 
} 
相關問題