2012-12-05 49 views
0

我有一個問題。 我實現了一個表格視圖。在didSelectRowAtIndexPath方法我增加細胞的高度和一個TextView添加到該小區的contentView。但是,如果我向下滾動表格視圖(例如10個單元格),我將再次看到相同的文本視圖。 你能幫我嗎?爲什麼一個UITableViewCell的子視圖中添加不正確?

這裏的一些代碼,爲了更好地理解這個問題:

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    if(selectedIndex == indexPath.row) 
    { 
     return CELL_HEIGHT * 5; 
    } 
    return CELL_HEIGHT; 
} 

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    [tableView deselectRowAtIndexPath:indexPath animated:TRUE]; 
    UITableViewCell *cell = [aTableView cellForRowAtIndexPath:indexPath]; 
    if (selectedIndex == indexPath.row) 
    { 
     selectedIndex = -1; 
     [[cell.contentView viewWithTag:COOL_TAG] removeFromSuperview]; 
    } 
    else 
    { 
     UITableViewCell *previousCell = [aTableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:selectedIndex inSection:0]]; 

     if ([previousCell.contentView viewWithTag:COOL_TAG]) 
     { 
      [[previousCell.contentView viewWithTag:COOL_TAG] removeFromSuperview]; 
     } 
     selectedIndex = indexPath.row; 
     UITextView *text = [[UITextView alloc] initWithFrame:CGRectMake(10, 45, 255, 180)]; 
     [text.layer setBackgroundColor:[[UIColor whiteColor] CGColor]]; 
     [text.layer setBorderColor:[[UIColor grayColor] CGColor]]; 
     [text.layer setBorderWidth:1.0f]; 
     [text.layer setCornerRadius: 8.0f]; 
     [text.layer setMasksToBounds:YES]; 
     [text setEditable:NO]; 
     text.text = [questionArray objectAtIndex:indexPath.row]; 
     text.tag = COOL_TAG; 
     [cell.contentView addSubview:text]; 
    } 

    [tableView beginUpdates]; 
    [tableView endUpdates]; 
} 

提前感謝!

+0

alloc if if(cell == nil){.....} – NANNAV

回答

2

的問題是,在細胞被重用。因此,當您向下滾動添加textview的單元格時,會在另一行中重用。

我認爲解決這個最好的方法是將TextView的單元添加cellForRowAtIndexPath方法中。

然後,你需要創建您在其中定義,如果該行應顯示TextView的或者不是數組。然後在didselect方法中,更改數組值並更新表。

請注意,檢查應在如果(細胞==零)外發生檢查中的cellForRowAtIndexPath,否則將不被要求重複使用的細胞。

+0

謝謝你很好的解釋。 – likecatfood

0

創建viewDidLoad中TextView的,並將其添加到CellForRow method.That的實現代碼如下電池可能會解決你的問題

+0

不確定。它只是在表視圖初始化之後添加文本視圖。我需要添加它當小區用戶水龍頭.. – likecatfood

+0

雅只需添加文本視圖變量DidselectRow方法,而不是cellForRow.It LL工作fine.i只是測試它 – sujay

+0

感謝,爲我的作品 – likecatfood

0

試試這個代碼,因爲在你的情況的電池單元resused

靜態的NSString * CellIdentifier = @ 「YourCell」;

YourCell *cell = (YourCell *) [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 
if (cell == nil) { 

    NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:@"YourCell" owner:self options:nil]; 

    for (id currentObject in topLevelObjects){ 
     if ([currentObject isKindOfClass:[UITableViewCell class]]){ 
      cell = (YourCell *) currentObject; 
      break; 
     } 
    } 
} 
相關問題