我有一个列表,其中显示一个名称和一个标题为“关注”的按钮。当我点击按钮时,标题应更改为“取消关注”。如果再次点击按钮,标题将再次更改为“关注”。这工作正常,但是当我滚动表格时,其他单元格的标题也会由于单元格的重用而改变。

代码如下:

  - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

    static NSString *CellIdentifier = @"AuthorsListCell";
    AuthorsListTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier
                                                                     forIndexPath:indexPath];
    dic_eachAuthor = [[_arr_authors objectAtIndex:indexPath.row] mutableCopy];

    cell.lbl_authorName.text = [dic_eachAuthor objectForKey:@"name"];
    cell.btn_followOrUnfollow.tag = indexPath.row;

    if([dic_eachAuthor valueForKey:@"follow"]){
        [cell.btn_followOrUnfollow setTitle:@"UnFollow" forState:UIControlStateNormal];
    }
    else{

        [cell.btn_followOrUnfollow setTitle:@"Follow" forState:UIControlStateNormal];
    }

    // action button method declarations
    [cell.btn_followOrUnfollow addTarget:self action:@selector(followOrUnfollow:) forControlEvents:UIControlEventTouchUpInside];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;

    return cell;
}


    -(void)followOrUnfollow:(UIButton *)sender
{
    if ([sender.titleLabel.text isEqualToString:@"Follow"]) {
        [sender setTitle:@"UnFollow" forState:UIControlStateNormal];
        [dic_eachAuthor setValue:@"1" forKey:@"follow"];

    }
    else if ([sender.titleLabel.text isEqualToString:@"UnFollow"]) {
        [sender setTitle:@"Follow" forState:UIControlStateNormal];
        [dic_eachAuthor setValue:nil forKey:@"follow"];


    }


}

请提出一些建议,以防止电池重复使用。

最佳答案

在cellForRowAtIndexPath中的followOrUnfollow中也添加此条件

if ([sender.titleLabel.text isEqualToString:@"Follow"]) {
        [sender setTitle:@"UnFollow" forState:UIControlStateNormal];

    }
    else if ([sender.titleLabel.text isEqualToString:@"UnFollow"]) {
        [sender setTitle:@"Follow" forState:UIControlStateNormal];


    }

关于ios - TableView单元重用导致滚动时更改按钮标题,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/30972724/

10-11 19:23
查看更多