2012-12-05 46 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; 
     } 
    } 
} 
相关问题