如何指定行的高度?

我想实现一个tableview,它显示特定行的可扩展单元格,因此我创建了自定义表格单元格,如果将其expandContent设置如下,将扩展它:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *CellIdentifier = @"Cell"; CustomCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; NSString *shouldExpand = [self.datasource objectAtIndex:indexPath.row]; if([shouldExpand isEqualToString:@"expand"]){ [cell setExpandContent:@"Expand"]; } else{ [cell setTitle:@"a line"]; } return cell; } 

但是,为了告诉tableview行高,我需要实现以下代码:

 - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath { CustomCell *cell = [self tableView:tableView cellForRowAtIndexPath:indexPath]; return [cell cellHeight]; } 

问题是heightForRowAtIndexPath方法将调用1000次tableView:cellForRowAtIndexPath:如果我的数据源包含1000个数据,并且它花费了太多时间。

如何解决问题?

不,你应该首先找到单元格的大小,然后发送高度计算,不要调用tableView:cellForRowAtIndexPath:它将导致递归,首先计算并发送高度。 例如

  //say suppose you are placing the string inside tableview cell then u need to calculate cell for example NSString *string = @"hello world happy coding"; CGSize maxSize = CGSizeMake(280, MAXFLOAT);//set max height CGSize cellSize = [self.str sizeWithFont:[UIFont systemFontOfSize:17] constrainedToSize:maxSize lineBreakMode:NSLineBreakByWordWrapping];//this will return correct height for text return cellSize.height +10; //finally u return your height 

如何解决问题?

如果你真的有1000行,你应该考虑使用动态行高,因为即使你想出一个快速的方法来确定行高,表仍然需要分别询问每行的高度。 (事实上​​,如果你真的有1000行,你应该重新考虑你的整个设计 – 用线性界面查看的数据太多了。)

如果必须对大量行使用动态行高,则至少需要找到一种快速方法来确定高度而不创建整个单元格。 也许您可以确定影响行高的因素,并提出一种非常简化的计算高度的方法。 如果你不能这样做,那么计算每行的高度一次然后用行数据保存结果可能是有意义的,这样你就不必再次计算它直到数据发生变化。

这是我用来动态设置UITableViewCell高度的代码:

 - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath { NSDictionary* dict = [branchesArray objectAtIndex:indexPath.row]; NSString* address = [NSString stringWithFormat:@"%@,%@\n%@\n%@\n%@",[dict objectForKey:@"locality"],[dict objectForKey:@"city"],[dict objectForKey:@"address"],[dict objectForKey:@"contactNumber"], [dict objectForKey:@"contactEmail"]]; CGSize constraint = CGSizeMake(220, MAXFLOAT); CGSize size = [address sizeWithFont:[UIFont fontWithName:@"Helvetica" size:14.0f] constrainedToSize:constraint lineBreakMode:NSLineBreakByWordWrapping]; CGFloat height1 = MAX(size.height, 110.0f); return height1+20; } 

以及设置框架 – (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath也