在IOS7以后,出现了自动计算高度的方法。
systemLayoutSizeFittingSize。但是这个得到的是contentView的高度,所以cell的高度还要再+1.
在计算出高度之后,可以保存在数组中,或者在这个cell中有关CGFloat属性,来保存当前的cell的model所占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;
- }
在计算cell上具有UITextView的时候,由于UITextView的高度再init后是不会自己改变的。所以,要计算出UITextView所占的高度。
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
C2 *cell = (C2 *)self.prototypeCell;
cell.t.text = [self.tableData objectAtIndex:indexPath.row];
CGSize size = [cell.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize];
CGSize textViewSize = [cell.t sizeThatFits:CGSizeMake(cell.t.frame.size.width, FLT_MAX)];
CGFloat h = size.height + textViewSize.height;
h = h > 89 ? h : 89; //89是图片显示的最低高度, 见xib
NSLog(@"h=%f", h);
return 1 + h;
}
详情资料参考:
http://www.cocoachina.com/industry/20140604/8668.html