ViewWIthTag返回nil(仅返回一次对象)

时间:2015-07-27 19:19:50

标签: ios uitableview

我在Storyboard中有标识符的单元格和带标记的相应对象。第一次调用cellForRowAtIndexPath时,viewWIthTag返回对象ok。例如,下一次btnCompartilhar是零。

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

    NSString *sectionTitle = [sectionsTitles objectAtIndex:indexPath.section];
    NSArray *secAtt = [attractions objectForKey:sectionTitle];

    Evento *evento = (Evento*)[secAtt objectAtIndex:indexPath.row];

    UITableViewCell *cell = nil;
    if(evento.listaImagens && [evento.listaImagens count] > 0) {
        cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath];
    }
    else {
        cell = [tableView dequeueReusableCellWithIdentifier:@"CellSemFoto" forIndexPath:indexPath];
    }

    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];



    UIButton *btnCompartilhar = (UIButton *)[cell.contentView viewWithTag:40];
    [btnCompartilhar.titleLabel setHidden:YES];
    btnCompartilhar.titleLabel.text = sectionTitle;
    btnCompartilhar.tag = indexPath.row;
    [btnCompartilhar addTarget:self action:@selector(compartilharClick:) forControlEvents:UIControlEventTouchDown];
    return cell;
}

我执行了命令po [cell.contentView recursiveDescription]并发现带有标签40的Button仅在第一次出现。但所有其他对象都是时候

1 个答案:

答案 0 :(得分:0)

调用btnCompartilhar.tag = indexPath.row;会更改标记,以便下次重复使用该单元时无法再找到它。

您不应该依赖viewWithTag:,而是应该创建自定义UITableViewCell子类并添加允许您访问所需视图的属性。如果需要,单元格还可以包含行号等附加信息。

请注意,您当前的方法存在其他问题,例如多次添加目标和操作,这也不是一个好主意。

相关问题