首页 文章

如何动态调整UITableViewCell高度

提问于
浏览
57

我有经典的UITableView分组,每个单元格内都有可编辑的UITextViews . 这个文本视图可以是单行或多行的,我希望单元格在用户写入时增加其高度,文本开始换行 .

我的问题是: do I need to reload the whole table just to increase the height of a cell? Isn't there any other method?

我一直在搜索,以前的答案和教程只是讨论如何计算文本高度,如何实现heightForRowAtIndexPath ...我已经知道的事情 . 我担心的是,为了达到我想要的效果,每次用户输入一个新角色时,我都必须计算高度并重新加载表格,我觉得这个角色并不干净或高效 .

谢谢 .

4 回答

  • 60

    您不必总是重新加载整个表 . 您只需重新加载那一行即可 .

    [tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:[NSIndexPath indexPathForRow:0 inSection:0]] withRowAnimation:UITableViewRowAnimationFade];
    
  • 27
    [tableView beginUpdates];
    [tableView endUpdates];
    
  • 5

    更具体地说,是的,你必须实现 tableView:heightForRowAtIndexPath: 来计算新的高度,然后按照rickharrison所说并调用 [tableView reloadRowsAtIndexPaths:withRowAnimation] . 假设您的细胞可以具有扩展的高度和正常的高度,并且您希望它们在敲击时生长 . 你可以做:

    -(CGFloat)tableView:(UITableView*)tableView heightForRowAtIndexPath:(NSIndexPath*) indexPath 
    {
        if ([expandedPaths containsObject:indexPath]) {
            return 80;
        } else {
            return 44;
        }
     }
    
    -(void)tableView:(UITableView*) didSelectRowAtIndexPath:(NSIndexPath*) indexPath
    {
        [expandedPaths addObject:indexPath];
        [tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }
    
  • 83

    -reloadRowsAtIndexPaths:withRowAnimation 没有调整UITableViewCell高度,即使我更改了Cell的框架 . 只有当我用 -reloadData 跟随它时它才有效:

    [tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:[NSIndexPath indexPathForRow:0 inSection:0]] withRowAnimation:UITableViewRowAnimationFade];
    [tableView reloadData];
    

相关问题