2013-07-24 20 views
0

我在Interface Builder中創建了UITableViewCell併爲其創建了一個子類。在它內部,我需要在標籤中顯示抽獎結果。我不知道我會得到多少結果,所以我不能在IB中爲它創建標籤,所以我在cellForRowAtIndexPath內部創建它們。所以現在發生的事情是,當細胞被重用時,我一直在子視圖上創建子視圖。UITableViewCell中UILabels的數量未知

我曾想過在Cell子類的Interface Builder \ awakeFromNib中創建標籤,並用它們的標籤填充它們,但我不知道會有多少標籤。

什麼是解決它的好方法?

有沒有一種方法可以刪除單元格的內容,一旦它超出了屏幕區域?

- (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; 
} 
+0

在回答做「有沒有辦法來消除對細胞的含量,一旦它在屏幕區域的?」,沒有。因爲一旦一個單元格出現在屏幕區域中,它就不再存在。 – Tim

回答

1

如果要添加子視圖的細胞,而不是使用默認的標籤,你需要刪除已有的細胞與像這樣子視圖:

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

希望它能幫助。

+0

這是一個不錯的解決方案。讓我看看我是否理解正確。基本上會發生的是,在'cellForRowAtIndexPath'的開頭我會檢查單元格是否已經有子視圖。如果確實如此,那麼'while'會將它清空,以便爲新內容做好準備? – Segev

+0

確切!我經常使用這個解決方案,因爲我通常添加自定義視圖到我的tableviewcells –

+0

嗯..放棄它!我想知道這是不是很好的做法。 – Segev

1

無論是否重複使用,您都將每次添加UILabels。您只需在單元格創建時添加UILabels

這需要稍微優雅的解決方案,儘管每次標籤的數量都會有所不同。

也許在IB中添加一個UIView容器,該容器將保存您所有動態創建的UILabels,並且每次刪除所有UILabels

例如

for (UILabel *label in cell.labelContainer.subviews) { 
    [label removeFromSuperview]; 
} 
1

有在這種計算策略的是每次的單元被裝載的標籤將在上面的細胞中添加及以上一遍又一遍,wheenever cellForrowAtIndexpath:是called.To避免創建和加入的問題UILabel必須在if(細胞==零)部分

+0

我不能在storyBoard原型UITableViewCell中使用cell = nil。它永遠不會被訪問。 – Segev

+0

然後不要在這裏使用故事板原型或驅動一個新的邏輯來分配只有一次 –