如何动态调整UITableViewCell高度

时间:2010-06-18 11:56:44

标签: iphone uitableview resize uitextview

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

我的问题是:我是否需要重新加载整个表格以增加单元格的高度?没有其他方法吗?

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

感谢。

4 个答案:

答案 0 :(得分:83)

[tableView beginUpdates];
[tableView endUpdates];

答案 1 :(得分:62)

您并不总是需要重新加载整个表格。您只需重新加载那一行即可。

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

答案 2 :(得分:27)

更具体地说,是的,你必须实现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];
}

答案 3 :(得分:5)

即使我更改了Cell的框架,

-reloadRowsAtIndexPaths:withRowAnimation也没有调整UITableViewCell高度的大小。它仅在我使用-reloadData

跟随它时才起作用
[tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:[NSIndexPath indexPathForRow:0 inSection:0]] withRowAnimation:UITableViewRowAnimationFade];
[tableView reloadData];
相关问题