如何指定行的高度? [英] how to specify height of row?
问题描述
我想实现一个tableview,它显示特定行的可扩展单元格,因此我创建了自定义表格单元格,如果将其expandContent设置如下,将会展开:
I want to implement a tableview which shows an expandable cell for a specific row, so I create my custom table cell which will be expanded if setting its expandContent as following:
- (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行高,我需要实现以下代码:
however, in order to tell tableview the row height, I need to implement the following code:
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
CustomCell *cell = [self tableView:tableView cellForRowAtIndexPath:indexPath];
return [cell cellHeight];
}
问题是heightForRowAtIndexPath方法会调用1000次tableView:cellForRowAtIndexPath:if my datasource包含1000个数据,花费的时间太长。
The problem is heightForRowAtIndexPath method will call 1000 times of tableView:cellForRowAtIndexPath: if my datasource contains 1000 data, and it cost too much time.
如何解决问题?
推荐答案
没有你应该首先找到单元格的大小然后发送高度计算,不要调用tableView:cellForRowAtIndexPath:它将导致递归,首先计算并发送高度。例如
no u should find the size of cell first then send the hight calculated, dont call tableView:cellForRowAtIndexPath: it will results in recursion instead, first calculate and send the height . for example
//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
这篇关于如何指定行的高度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!