How can I add a UITapGestureRecognizer to a UILabel inside a table view cell?

后端 未结 10 1456
萌比男神i
萌比男神i 2021-02-04 00:43

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 assoc

10条回答
  •  广开言路
    2021-02-04 01:29

    Doing this works without problems:

    - (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;
          ....
         }
    }
    

    even in the case in which creates the UILabel with IB

提交回复
热议问题