如何在不指定估计行高的情况下使用iOS自动resize的单元格?
我想利用自动布局在iOS 8中自动照顾我的细胞高度,但我讨厌估计行高度滚动(跳动,滚动位置不可预知,等等)如何挑剔。
有没有办法不使用估计,以便表视图预先计算所有的行高,就像它在iOS 7之前(不是太多的单元格,所以不是一个性能问题),但使用iOS 8的高度自动计算?
编辑:
如果不使用此属性,则无法使用dynamicresize。 estimatedRowHeight
告诉系统使用dynamic大小,假设您在单元格中使用了自动布局。
观看WWDC 2014video226。
//
非常简单 – 在Storyboard中创build原型单元格,为superview顶部/底部(也就是单元格内容视图)添加约束,这意味着您的子视图具有顶部/底部约束,必要时将“推入”单元大小。
将TableView和Cell高度都设置为Default。 如果这是问题(自动布局需要比默认的44点更高的高度),那么请确保在代码中执行它: tableView.rowHeight = UITableViewAutomaticDimension
不要忘记设置estimatedRowHeight
告诉系统你想要dynamicresize启用。
自动resize需要您提供估计的行高,但您可以使用自动布局预先计算行高。
要做到这一点,你需要一个“虚拟”单元格填充数据的大小,你想要计算的单元格。 然后,您可以使用自动布局为您完成工作:
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath { static YourCell *dummy = nil; static NSLayoutConstraint *widthConstraint = nil; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ UINib *nib = [UINib nibWithNibName:@"YourCell" bundle:nil]; dummy = [[nib instantiateWithOwner:nil options:nil] firstObject]; widthConstraint = [NSLayoutConstraint constraintWithItem:dummy.contentView attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:nil attribute: NSLayoutAttributeWidth multiplier:1.0 constant:320.0]; widthConstraint.priority = 750; //Good idea to lower priority of this constraint so it doesn't interfere with whatever table view sets internally [dummy addConstraint:widthConstraint]; }); //account for current table view width widthConstraint.constant = tableView.bounds.width; //... //Configure dummy cell here //... CGSize size = [dummy systemLayoutSizeFittingSize:UILayoutFittingCompressedSize]; return size.height; }
你也可以使用
- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath
要么
_activityTable.estimatedRowHeight = [CompanyEventCell cellHeight];