iOS UITableViewCells rows recycled and tag not working

后端 未结 2 1883
广开言路
广开言路 2021-01-25 22:34

I would like to seek some help in setting tag for buttons in cells. This is a question with a link to the previous I posted : iOS Using NSDictionary to load data into section an

相关标签:
2条回答
  • 2021-01-25 22:54

    I could not see your cell.renewButton being assigned a selector method (the method that should be triggered on tapping the button).

    [cell.renewButton addTarget:self action:@selector(renewButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
    

    Also, I would specify a tag number with an offset, as tag of 0 is almost like not tagging at all. First row of tableView will give indexPath.row = 0.

    Above your code,

    #define OFFSET 100 /* Or any number greater than 0 */
    

    In cellForRowAtIndexPath,

    ...
    [cell.renewButton addTarget:self action:@selector(renewButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
    cell.renewbutton.tag = indexPath.row + OFFSET;
    ...
    

    In the renewButtonPressed method,

    -(void)renewButtonPressed:(id)sender
    {
        tappedNum = [sender tag] - OFFSET;
        /* do your stuff */
    }
    

    tappedNum will give you the row that the button is tapped, starting with 0.

    0 讨论(0)
  • 2021-01-25 23:00

    You cannot use the button tags, as these will be the same as those of the cells they have been recycled from. Instead, use the indexPath to determine on which row you are and use that directly. No need to go through the button tag.

    0 讨论(0)
提交回复
热议问题