在实际项目中,根据后台返回的数据动态显示每一条数据,选择用UITableView呈现时,要考虑UITableViewCell高度问题。
在方法 -(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath 中设置固定大小肯定不能满足需求,所以在此方法中我通常选择在
UITableViewCell 中创建一个类方法将所需的数据入参,计算出高度。这样的话,在 UITableViewCell 创建时还要走一次类似的过程,增加了开销。 我的解决方法是,通过直接返回UITableViewCell在创建时定下来的自身高度大小。代码如下:
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
id data = [self.MActiveModelArr objectAtIndex:indexPath.row];
YZActiveDetailTableCell * cell = (YZActiveDetailTableCell * )[self tableView:tableView preparedCellForIndexPath:indexPath withData:data];
return cell.frame.size.height;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
id data = [self.MActiveModelArr objectAtIndex:indexPath.row];
YZActiveDetailTableCell * cell = (YZActiveDetailTableCell * )[self tableView:tableView preparedCellForIndexPath:indexPath withData:data];
if ((indexPath.row ) == [_mActiveModelArr count]-1 ) {
cell.MLineView.hidden = true;
}
[cell setSelectionStyle:UITableViewCellSelectionStyleNone];
return cell;
}
- (UITableViewCell *)tableView:(UITableView *)tableView preparedCellForIndexPath:(NSIndexPath *)indexPath withData:(id)data
{
NSString *key = [NSString stringWithFormat:@"%ld-%ld",(long)indexPath.section, (long)indexPath.row];
//try to get the cell from cache
YZActiveDetailTableCell *cell = [_mCellCache objectForKey:key];
if (!cell)
{
cell = [[YZDetailReplyTableCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"replayYZCell" ];
[cell updateWithNote:data];
// cache it, if there is a cache
[_mCellCache setObject:cell forKey:key];
}
return cell;
}
我们将创建的 UITableViewCell 加入到NSCache 中,这样开销减少了一半,而且NSCache可根据内存的要求浮动变化,也解决了因为在 UITableViewCell 中加入表情图片过多出现卡的问题。