【发布时间】:2014-03-24 22:05:48
【问题描述】:
我尝试在自定义 uitableviewcell 中使用自动布局 并尝试根据这个SO主题实现动态高度
Using Auto Layout in UITableView for dynamic cell layouts & variable row heights
但我的单元格是由 xib 文件创建的。所以方法有些不同 这是我在 heightForRowAtIndexPath 中的代码
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
myDataItem *item= [[data items] objectAtIndex:[indexPath row]];
CustomCell *cell = [self.offscreenCells objectForKey:@"CustomCell"];
if (!cell) {
cell = [CustomCell alloc] init];
[self.offscreenCells setObject:cell forKey:@"CustomCell"];
}
[cell.commentView setText:item.comment];
[cell.displayNameView setText:item.displayNameOfItemOwner];
[cell.timeAgoView setText:item.timeAgo];
[cell.imageView setImage:[UIImage imageNamed:@"sis_profile_placeholder"]];
cell.bounds = CGRectMake(0.0f, 0.0f, CGRectGetWidth(tableView.bounds), CGRectGetHeight(_prototypeCell.bounds));
[cell setNeedsLayout];
[cell layoutIfNeeded];
CGFloat height = [cell.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize].height;
return height+1; }
我从 [cell.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize] 得到的高度总是“nil” " 当我尝试调试时,我发现我的 customcell 的所有子视图都是“nil”,但单元格本身不是“nil”。这可能是因为我的 customCell 是由 nib 制作的,当我执行 [[CustomCell alloc] init] 时,单元格没有完全创建。
但我确实尝试将方法更改为 cell = [_tableView dequeueReusableCellWithIdentifier:@"CustomCell"];
结果还是一样。每个子视图都是 nil 。这使高度返回为零,并使我的 tableView 显示不正确。有没有办法解决这个问题?
我尝试在 AutoLayout 上制作这些。实际上,在以前的版本中,我没有使用 AutoLayout 并手动计算单元格高度。它确实工作得很好。无论如何,我只想尝试 AutoLayout。
请帮忙。在此先感谢
【问题讨论】:
-
如果您打算从笔尖加载单元格,
cell = [CustomCell alloc] init];将不起作用。查看this question 了解如何执行此操作。 -
谢谢。我现在可以从 xib 创建 CustomCell。但是 [cell.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize] 仍然返回 nil
-
该方法的返回类型是 CGFloat,而不是 id,所以它不应该返回 nil。但是,如果它返回 0.0,则您的约束可能有问题。同样,我的建议是在代码中做你的约束,因为它更容易调试和正确。
-
对不起,我的意思是零。 Cell.contentView systemLayoutSizeFittingSize 不起作用,但是当我更改为 cell.commentView 时,它确实返回了有效值。因为评论视图只是具有动态高度的视图,所以我使用它的返回值来计算 heightForRow
-
我也遇到了同样的问题,请问您解决了吗?
标签: ios objective-c uitableview autolayout