在xib的新时代,设置好约束一切都可以根据内容自适应.Tableview是个例外.
Tableview的问题:
1.Tableview在iOS7以下是个例外。iOS7以下delegate方法
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath*)indexPath {
//先设置好所有的内容,这是必须的(否则得到的高度也是不准确的)
self.prototypeCell.contentLabel.text = [self.details objectAtIndex:indexPath.row];
//设置cell的临时宽度约束(不设置这个,居然是没法获取到正确值的)
CGFloat contentViewWidth = [UIScreenmainScreen].bounds.size.width;
NSLayoutConstraint *widthFenceConstraint = [NSLayoutConstraintconstraintWithItem:self.prototypeCell.contentViewattribute:NSLayoutAttributeWidthrelatedBy:NSLayoutRelationEqualtoItem:nilattribute:NSLayoutAttributeNotAnAttributemultiplier:1.0constant:contentViewWidth];
[self.prototypeCell.contentViewaddConstraint:widthFenceConstraint];
// Auto layout engine does its math //获取到内容高度(核心方法)
CGFloat fittingHeight = [self.prototypeCell.contentViewsystemLayoutSizeFittingSize:UILayoutFittingCompressedSize].height;
//删除约束
[self.prototypeCell.contentViewremoveConstraint:widthFenceConstraint];
//获取到修正的高度,就是那个分割线的高度吧
return (fittingHeight += 1.0 / [UIScreen mainScreen].scale);
}
由于在- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath*)indexPath;方法里的时候这时候Tableview的cell还没有创建,这里需要一个专门用来计算的cell,所以我创建了一个属性专门用来存计算的cell.
PS:这里只是它的大概实现,当然你必须设置好约束.
封装之后的库见:https://github.com/forkingdog/UITableView-FDTemplateLayoutCell
iOS8上的解决方法:
//iOS8实现自适应就是这么简单,连heightForRowAtIndexPath方法
都不要实现只要设置好top和bottom约束即可.
self.mainTableView.estimatedRowHeight =40;
self.mainTableView.rowHeight =UITableViewAutomaticDimension;
ps:例子:https://github.com/songxuhua/TestForAutoLabel
参考:http://blog.sunnyxx.com/2015/05/17/cell-height-calculation/
iOS TableView 自适应

本文介绍在iOS中如何使TableView的Cell高度自适应内容。对于iOS7及以下版本,通过设置临时宽度约束并利用Auto Layout计算得出高度;而在iOS8及以上版本,则可通过设置estimatedRowHeight与rowHeight为UITableViewAutomaticDimension轻松实现。
7245

被折叠的 条评论
为什么被折叠?



