Detecting which UIButton was pressed in a UITableView

前端 未结 26 2937
小蘑菇
小蘑菇 2020-11-22 00:40

I have a UITableView with 5 UITableViewCells. Each cell contains a UIButton which is set up as follows:

- (UITableView         


        
26条回答
  •  一整个雨季
    2020-11-22 01:06

    you can use the tag pattern:

    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
    {
         NSString *identifier = @"identifier";
         UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
         if (cell == nil) {
             cell = [[UITableView alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
             [cell autorelelase];
    
             UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(10, 5, 40, 20)];
             [button addTarget:self action:@selector(buttonPressedAction:) forControlEvents:UIControlEventTouchUpInside];
             [button setTag:[indexPath row]]; //use the row as the current tag
             [cell.contentView addSubview:button];
    
             [button release];
         }
    
         UIButton *button = (UIButton *)[cell viewWithTag:[indexPath row]]; //use [indexPath row]
         [button setTitle:@"Edit" forState:UIControlStateNormal];
    
         return cell;
    }
    
    - (void)buttonPressedAction:(id)sender
    {
        UIButton *button = (UIButton *)sender;
        //button.tag has the row number (you can convert it to indexPath)
    }
    

提交回复
热议问题