2013-12-09 162 views
0

我创建的细胞,可以展开和折叠,当电池扩展I加2子视图,当细胞处于折叠状态删除这些子视图2。看看代码:如何删除以前的子视图,并添加新的子视图的UITableViewCell

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { 
    if(selectedIndex == indexPath.row){ 
     selectedIndex = -1; 

     UITableViewCell *cell = [self.tblView cellForRowAtIndexPath:indexPath]; 
     [[cell viewWithTag:TAG_KHMER] removeFromSuperview]; 
     [[cell viewWithTag:TAG_KOREAN] removeFromSuperview]; 

     //[tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade]; 

     [self.tblView beginUpdates]; 
     [self.tblView endUpdates]; 

     return; 
    } 

    if(selectedIndex >= 0){ 
     NSIndexPath *previousPath = [NSIndexPath indexPathForRow:selectedIndex inSection:0]; 
     selectedIndex = indexPath.row; 
     UITableViewCell *cell = [self.tblView cellForRowAtIndexPath:previousPath]; 
     [[cell viewWithTag:TAG_KHMER] removeFromSuperview]; 
     [[cell viewWithTag:TAG_KOREAN] removeFromSuperview]; 
     //[tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade]; 
    } 

    VocabularyController *vc = [self.vocabularyInfo objectAtIndex:indexPath.row]; 
    UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath]; 

    UILabel *khmerLabel = [[UILabel alloc] init]; 
    khmerLabel.text = vc.khmer; 
    khmerLabel.font = [UIFont fontWithName:@"Hanuman" size:17]; 
    [khmerLabel setNumberOfLines:0]; 
    khmerLabel.tag = TAG_KHMER; 
    khmerLabel.frame = CGRectMake(20, 45, 300, 300); 

    UILabel *koreanPro = [[UILabel alloc] init]; 
    koreanPro.text = vc.korean; 
    [koreanPro setNumberOfLines: 0]; 
    koreanPro.tag = TAG_KOREAN; 
    koreanPro.frame = CGRectMake(20, 315, 300, 300); 

    [cell addSubview:khmerLabel]; 
    [cell addSubview:koreanPro]; 

    selectedIndex = indexPath.row; 

    //[tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade]; 

    [self.tblView beginUpdates]; 
    [self.tblView endUpdates]; 

} 

发生了什么事是细胞似乎并没有删除前一个。它会在旧文本上显示新文本,但是当我再次单击同一单元格两次,然后单元格可以使文本变得更好。

任何人都可以帮助我如何正确显示它。

enter image description here

点击两倍于细胞后。

enter image description here

回答

2

不要尝试,并添加子视图这样的 - 它会导致混乱,因为你已经发现了UITableView回收细胞。

相反,创建自己的自定义UITableViewCell的子类,可以为您所需要的各种状态之间进行切换,并拥有所有子视图已经成立。您可以通过多种方式来完成此操作 - 如果您使用的是故事板,则可以使用原型单元格,也可以使用NIB,也可以完全使用代码创建自定义子类(无论您最喜欢哪个)。

基本上,不要在您的表视图委托/数据源调用中为您的单元添加子视图。创建一个自定义的子类,你会发现一切,更容易。

+0

我的工作差不多完成了。 我已经创建了自定义UITableViewCell并将3标签放入单元格中,如图所示。 但有一件事,我试图解决的是: 第2标签包含长字符串(如:它有大约3行),我试图改变它的框架,但它的高度没有改变。第三个标签仍然保持不变。 实际上,第二个标签高度必须更大,第三个标签必须在此之后。 你能告诉我如何解决这个问题吗? 非常感谢。 –

相关问题