使用UITableViewCells和动态高度自动布局
所以我看了this answer。但我仍然没有得到正确的iOS7返回的高度。我有一个表格视图,我在自动布局中放置了一个相当复杂的单元格。每当我尝试覆盖heightForRowAtIndex
(使其与iOS7兼容)时,我会得到似乎无法正确计算的行高。当我不覆盖heightForRowAtIndex
一切都很好,但它不适用于iOS7。我也尝试使用xib自动布局整个事情。我的DipticCell.m中没有任何逻辑。全部在UITableView子类中。使用UITableViewCells和动态高度自动布局
-(id)init{
//Implementation details go BELOW
self.dataSource = self;
self.delegate = self;
[self registerNib:[UINib nibWithNibName:@"DipticCell" bundle:nil] forCellReuseIdentifier:@"dipticCell"];
[self registerClass:[UITableViewCell class] forCellReuseIdentifier:@"cell2"];
self.rowHeight = UITableViewAutomaticDimension;
offScreenCells = [[NSMutableDictionary alloc] init];
return self;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
NSString *reuseIdentifier = @"dipticCell";
if (indexPath.row > 0){
reuseIdentifier = @"cell2";
}
UITableViewCell *cell = [offScreenCells objectForKey:reuseIdentifier];
if (!cell) {
cell = [self dequeueReusableCellWithIdentifier:reuseIdentifier];
[offScreenCells setObject:cell forKey:reuseIdentifier];
}
[cell setNeedsUpdateConstraints];
[cell updateConstraintsIfNeeded];
cell.bounds = CGRectMake(0.0f, 0.0f, CGRectGetWidth(tableView.bounds), CGRectGetHeight(cell.bounds));
[cell setNeedsLayout];
[cell layoutIfNeeded];
CGFloat height = [cell.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize].height;
height += 1.0f;
return height;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
if (indexPath.row == 0){
DipticCell *cell = [tableView dequeueReusableCellWithIdentifier:@"dipticCell"];
if (cell == nil) {
cell = [[DipticCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"dipticCell"];
}
return cell;
}else{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell2"];
if (cell == nil) {
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"cell2"];
}
cell.textLabel.text = @"one";
return cell;
}
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return 10;
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
return 1;
}
只是为了确认一切都在contentView中。
此外,当我重写heightForRowAtIndexPath
我得到一个“无法同时满足的约束。”警告。但是当我不覆盖那东西似乎工作(这是有道理的,因为细胞应该适应内容的高度,现在我试图覆盖它的高度为1.)
这里是一个链接到项目,如果你想运行它。 AutoLayoutCells
大部分时间对我来说有效的是确保您有一条从单元格顶部到单元格底部的约束路径。
因此,如果您的手机作为三个标签:label1,label2,label3和全部应显示在彼此之下。比添加约束:
cell.top to label1.top
label1.bottom to label2.top
label2.bottom to label3.top
label3.bottom to cell.bottom
那样你的细胞的高度是由约束定义的。因此,请确保连接所有定义此链中单元格高度的子视图。
我加倍检查,一切都很好。就像我说的那样,当我取出heightForRowAtIndexPath位时,它可以工作,但是当我将它添加回来时,会错误地估计高度。 – 2014-09-25 18:27:47
链接的项目只是一个空的视图。它没有任何表格。 – 2014-09-25 17:10:20
固定。我不知道为什么它第一次没有正确推送... – 2014-09-25 17:36:38
如果我在下载它之后直接运行该项目,在iOS 8模拟器上,它无法正确显示。红色文本单元格被压缩。是不是应该在iOS 8上看起来不错?另外,UIScrollView的用途是什么?现在看起来空了。有时候滚动视图会在放入单元格时产生问题(因为UITableView是一个UIScrollView子类),你不能删除它吗? – 2014-09-26 10:06:53