基于两个子视图高度的自定义TableView单元格

TableView说明
tableView.rowHeight = UITableViewAutomaticDimension tableView.estimatedRowHeight = 60.0

单元格说明
我有一个单元格,在ContainerView中有2个标签(Title,Description),下面是一个ImageView。 单元高度将根据“说明标签”的内容而有所不同。
所有观点的对立

有两种情况我应该处理

  1. ContainerView.height大于(ImageView.height + ImageView.Top + ImageView.Bottom)。 这里单元格的高度将基于ContainerView.height
  2. ContainerView的高度小于(ImageView.height + ImageView.Top + ImageView.Bottom)。 在这里,我期望Cell应该考虑(ImageView.height + ImageView.Top + ImageView.Bottom)作为高度,并使ContainerView垂直居中Cell。
    预期结果在这两种情况下

问题
如果我为第一种情况设置约束,那么第二种情况不起作用,反之亦然(我知道通过去除ContrainerView.Top,Bottom并使其垂直居中到SuperView情况2的结果可以实现)

有没有办法通过使用同一套IB约束和UITableViewAutomaticDimension来实现预期的结果?

为图像视图提供固定的高度和宽度。 否则,让tableViewCell知道imageview的顶部和底部。 这样它可以计算出正确的细胞高度

首先确保你正在使用自定义单元格: https : //developer.apple.com/library/content/documentation/UserExperience/Conceptual/AutolayoutPG/WorkingwithSelf-SizingTableViewCells.html

使图像视图和容器视图对单元格的边缘进行顶部和底部约束,并使它们>=

或者,您可以尝试“水平堆栈视图”,并对单元格的每个边进行严格(最高优先级)约束。

使用这些代表,

 - (CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath { return 100; // height of default cell } - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath { return UITableViewAutomaticDimension; } 

编辑

试试这个。

你的视图层次应该是这样的

在这里输入图像说明

ImageView约束

在这里输入图像说明

添加一个视图,并将两个标签放入它。

标签容器的限制

在这里输入图像说明

标签标题约束

在这里输入图像说明

标签说明约束

在这里输入图像说明

编辑输出

在这里输入图像说明