我有一个 UITableViewCell
,其中包含一个带有垂直堆叠 View 的 UIStackView
。我已将 UITableViewAutomaticDimension
设置为 UITableView
的行高和估计高度。 UIStackView
的 subview 之一包含两个 UIImageViews
,如下所示:
小的是avatarImageView
,大的是messageImageView
。以下是限制条件:
avatarImageView
:
messageImageView
:
然后,我尝试在 cellForRowAt
的委托(delegate)方法中更新 messageImageView
的高度以匹配图像比例(并且我让宽度为 200px ImageView )。
let ratio = image.size.width / image.size.height
cell.messageImageViewHeightConstraint?.constant = 200 * ratio
例如,我正在尝试使用这张图片:
但它根本不起作用,图像占用了太多空间,并且由于某种原因头像 ImageView 最终被隐藏(单元格被红色包围,上面是一个只有文本的单元格,工作正常):
那么我在这里缺少什么?
感谢您的帮助!
最佳答案
与您的使用方式相比,您的比率
是相反的:
最简单的解决方法是除以 ratio
而不是乘以它:
let ratio = image.size.width / image.size.height
cell.messageImageViewHeightConstraint?.constant = 200 / ratio
或者,如果您愿意,可以更改ratio
计算:
let ratio = image.size.height / image.size.width
cell.messageImageViewHeightConstraint?.constant = 200 * ratio
关于ios - AutoLayout:在 UIStackView/UITableViewCell 中缩放 UIImageView 时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52030632/