自动计算UITableViewCell的高度

  • 需要用到一个新的API systemLayoutSizeFittingSize:来计算UITableViewCell所占空间高
    度。Cell的高度是在- (CGFloat)tableView:(UITableView )tableView
    heightForRowAtIndexPath:(NSIndexPath )indexPath这个UITableViewDelegate的方法
    里面传给UITableView的。
    *这里有一个需要特别注意的问题,也就是  问题。UITableView是一次性计算完所有
    Cell的高度,如果有1W个Cell,那么- (CGFloat)tableView:(UITableView )tableView
    heightForRowAtIndexPath:(NSIndexPath )indexPath就会触发1W次,然后才显示内
    容。不过在iOS7以后,提供了一个新方法可以避免这1W次调用,它就是-
    (CGFloat)tableView:(UITableView )tableView estimatedHeightForRowAtIndexPath:
    (NSIndexPath )indexPath。要求返回一个Cell的估计值,实现了这个方法,那只有显示
    的Cell才会触发计算高度的protocol. 由于systemLayoutSizeFittingSize需要cell的一个
    实例才能计算,所以这儿用一个成员变量存一个Cell的实列,这样就不需要每次计算Cell高度的时候去动态生成一个Cell实例,这样即方便也高效也少用内存,可谓一举三
    得。
  • 声明一个存计算Cell高度的实例变量
    @property (nonatomic, strong) UITableViewCell *prototypeCell; 
  • 初始化prototypeCell
    self.prototypeCell = [self.tableView
dequeueReusableCellWithIdentifier:@"C1"];
  • 计算Cell高度的实现
   - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:
(NSIndexPath *)indexPath {
 C1 *cell = (C1 *)self.prototypeCell;
 cell.t.text = [self.tableData objectAtIndex:indexPath.row];
 CGSize size = [cell.contentView
systemLayoutSizeFittingSize:UILayoutFittingCompressedSize];
 NSLog(@"h=%f", size.height + 1);
 return 1 + size.height;
} 
//UITableViewCell的高度要比它的contentView要高1,也就是它的分隔线的高度

猜你喜欢

转载自blog.csdn.net/icandyss/article/details/55260758