ios - AutoLayout:在 UIStackView/UITableViewCell 中缩放 UIImageView 时出现问题

标签 ios swift autolayout uistackview

我有一个 UITableViewCell,其中包含一个带有垂直堆叠 View 的 UIStackView。我已将 UITableViewAutomaticDimension 设置为 UITableView 的行高和估计高度。 UIStackView 的 subview 之一包含两个 UIImageViews,如下所示:

enter image description here

小的是avatarImageView,大的是messageImageView。以下是限制条件:

avatarImageView:

enter image description here

messageImageView:

enter image description here

然后,我尝试在 cellForRowAt 的委托(delegate)方法中更新 messageImageView 的高度以匹配图像比例(并且我让宽度为 200px ImageView )。

let ratio = image.size.width / image.size.height
cell.messageImageViewHeightConstraint?.constant = 200 * ratio

例如,我正在尝试使用这张图片:

enter image description here

但它根本不起作用,图像占用了太多空间,并且由于某种原因头像 ImageView 最终被隐藏(单元格被红色包围,上面是一个只有文本的单元格,工作正常):

enter image description here

那么我在这里缺少什么?

感谢您的帮助!

最佳答案

与您的使用方式相比,您的比率是相反的:

最简单的解决方法是除以 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/

相关文章:

ios - Swift:如何使用 "estimatedRowHeight"?Dynamic Cell Height Stange 错误

ios - 在自动布局中自动更新框架

ios - 如何在 iOS 中快速创建大文件

ios - 在 GADBannerView 内调整图像大小

ios - CLPlacemark位置也会提供地区信息,为什么?

ios - 在 ios 相关查询中对登录 View Controller 进行单元测试

ios - 如何获取 iPhone 的 UDID?

ios - 如何水平居中 UIView?

swift - 在 Firebase 中增加数据点的最简单方法?

ios - 如何为我的自定义 TabBarController 设置自定义 tabBar?