Two buttons in a UITableViewCell: How to tell which indexPath was selected?

前端 未结 2 1036
甜味超标
甜味超标 2021-01-13 10:08

I want to place two buttons in each table view cell. When I click on button number one I want the app to show an alert message: \"You tapped button1 at indexpath:3,0\". My

2条回答
  •  情歌与酒
    2021-01-13 10:32

    Using indexPath as the tag value is OK when you have only one button in a UITableCell but if you want to track more you can use modulo operator:

        - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:              
        (NSIndexPath *)indexPath {
        ...
        imageButton1.tag=indexPath.row*2; 
        [imageButton1 addTarget:self action:@selector(buttonPushed:)
        [cell.contentView addSubview:imageButton];
    
    
        ...
        imageButton2.tag=indexPath.row*2+1; 
        [imageButton2 addTarget:self action:@selector(buttonPushed:)
        [cell.contentView addSubview:imageButton];
    

    for the selector you can distinguish between the buttons and get the indexPath like this:

    -(void) buttonPushed:(id)sender{
     UIButton *button = (UIButton *)sender;
    
        switch (button.tag%2) {
            case 0:  // imageButton1 is pressed
    
    // to reach indexPath of the cell where the button exists you can use:
    //         ((button.tag-button.tag%2)/2)
    
            break;
    
            case 1: // imageButton2 is pressed
    
            break;
        }
    

    The example is for 2 buttons but you can adjust it according to the number of buttons.

提交回复
热议问题