iOS UITableViewCells rows recycled and tag not working

后端 未结 2 1924
广开言路
广开言路 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.

提交回复
热议问题