在我的应用程序中,它有大约数千个内容显示在tableView中。每个内容都有不同的高度,因为其中有一到三行UILabel。目前,它计算并返回tableView委托函数中每个单元格的高度:
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
它的计算方式是:
contentCell = (RSContentViewCell *)self.tmpCell;
UIFont *font = contentCell.myTextLabel.font;
width = contentCell.myTextLabel.frame.size.width + 30;
size = [contentStr sizeWithFont:font
constrainedToSize:CGSizeMake(width, CGFLOAT_MAX)
lineBreakMode:contentCell.myTextLabel.lineBreakMode];
height = size.height;
return height;
它可以工作但需要大约0.5秒来计算这些高度,因此用户体验不太好,因为应用程序在计算过程中没有响应。 那么正确的方法是什么?计算这些细胞高度的正确位置在哪里?
更新
数据来自服务器,并在进入表格视图时被请求。
答案 0 :(得分:1)
当您从服务器上传输数据时,无论如何都会有延迟。
=>我建议你在背景中计算高度,然后重新加载表格/删除微调器等。
// Method you call when your data is fetched
- (void)didReciveMyData:(NSArray *)dataArray {
// start background job
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
self.myCachedHeightArray = [[NSMutableArray alloc] initWithCapacity:[dataArray count]];
int i = 0;
for (id data in dataArray) {
float height;
// do height calculation
self.myCachedHeightArray[i] = [NSNumber numberWithFloat:height];// assign result to height results
i++;
}
// reload your view on mainthread
dispatch_async(dispatch_get_main_queue(), ^{
[self doActualReload];
});
});
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
return [[self.myCachedHeightArray objectAtIndex:indexPath.row] floatValue];
}
答案 1 :(得分:1)
我把它放入我的自定义单元子类中...所以代码不会使我的控制器混乱,对我使用的单元格是正确的。 (+它更适合MVC那种方式......单元格的高度是IMO的视图属性)
我不测量每个单元格,但使用静态方法 - 请参阅https://github.com/Daij-Djan/TwitterSearchExampleApp(ViewController和DDTweetTableViewCell类作为示例)
答案 2 :(得分:0)
您仍然必须在前端执行此操作,但只执行一次并将结果缓存到数组中并将其用于将来的调用。
即。第一次数组值为空时,计算它并将其存储在数组中。
下次数组有一个值时,不必计算就可以使用它。
答案 3 :(得分:0)
你如何设置/获取self.tmpCell?您是否将可重复使用的单元保存在属性中?
而是从单元格中获取文本并计算大小,您可以从单元格的数据源计算文本的大小。我的意思是你以某种方式设置cellForRowAtIndexPath:
中的文本(例如,来自数组)只需使用其中的文本来计算它。
对于框架:单元格具有相同的tableview宽度 对于字体:只需编写一个名为
的方法- (UIFont *)fontForCellAtIndexPath:(NSIndexPath *)indexpath
并从cellForRowAtIndexPath
使用它。如果您稍后更改文本字体,它会使您的工作更轻松。