0

UITableViewCell在 Interface Builder 中创建了一个并为它创建了一个子类。在里面我需要在标签中显示抽奖结果。我不知道我会得到多少结果,所以我不能在 IB 中为它创建标签,所以我在里面创建它们cellForRowAtIndexPath。所以现在发生了什么,当重用单元格时,我不断在子视图上创建子视图。

我考虑awakeFromNib在 Cell 子类的 Interface Builder \ 中创建标签,并使用它们的标签填充它们,但我不知道会有多少标签。

有什么好办法解决吗?

一旦超出屏幕区域,有没有办法删除单元格的内容?

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    //Where we configure the cell in each row
    id currentRaffle = [_winnings objectAtIndex:indexPath.row];
    RaffleResultCell *cell = [tableView dequeueReusableCellWithIdentifier:@"raffleResCell"];
    if (cell == nil) {
        cell = [[RaffleResultCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"raffleResCell"];
    }
    cell.prizeTitle.text = [currentRaffle valueForKey:@"title"];
    NSArray *winningNumbers = [[currentRaffle valueForKey:@"winningNumbers"] componentsSeparatedByString:@","];
    cell.numbOfRowsPerCell = 1+ [winningNumbers count]/4;
    int row =0;
    int col=0;
    for (int i=0;i<[winningNumbers count];i++)
    {
        UILabel *temp =[[UILabel alloc]initWithFrame:CGRectMake(70*row, 30*col, 70, 20)];
        temp.textAlignment = UITextAlignmentCenter;
        temp.font=[temp.font fontWithSize:14];
        temp.text = [NSString stringWithFormat:@"%@  ",[winningNumbers objectAtIndex:i]];
        [cell.winningNumbersView addSubview:temp];
        if(row<3)
        [cell.winningNumbersView addSubview:line];
        row++;
        if(row >3)
        {
            row=0;
            col++;
        }
    }

    return cell;
}
4

3 回答 3

1

如果您将子视图添加到单元格而不是使用默认标签,则需要删除已经具有单元格的子视图,如下所示:

while (cell.subviews.count != 0)
{
    [[cell.subviews objectAtIndex:0] removeFromSuperview];
}
// And then, add the new subviews

希望能帮助到你。

于 2013-07-24T10:04:58.633 回答
1

UILabels无论重用如何,您每次都在添加。您只需要添加UILabelsat 单元格创建。

这需要一个稍微更优雅的解决方案,但如果每次标签的数量会有所不同。

也许在 中添加一个UIView容器IB,它将保存您动态创建的所有内容,并且每次UILabels都将其删除。UILabels

例如

for (UILabel *label in cell.labelContainer.subviews) {
    [label removeFromSuperview];
}
于 2013-07-24T10:06:49.287 回答
1

这种方法存在一个问题,每次加载单元格时,标签都会在单元格中一遍又一遍地添加,无论何时调用。cellForrowAtIndexpath:为避免创建和添加UILabel 必须在 if(cell ==nil) 部分

于 2013-07-24T10:18:19.493 回答