我有一个 UITableViewCell
,它只包含一个 UIImageView
。我正在使用 UITableViewAutomaticDimension
,它适用于我的 tableview 中的所有其他单元格,除了这个 ImageView 单元格。
tableView.estimatedRowHeight = 100
tableView.rowHeight = UITableViewAutomaticDimension
我希望图像尽可能高,保持图像的纵横比并填充宽度。为此,我使用自动布局将 ImageView 的约束设置为固定到单元格的框架,并将 ImageView 的 contentMode 设置为 Aspect Fit。我将 UIImageView 的背景设置为红色。它上面的单元格是白色的。下面的实际图像是黑色的。
当我这样做时,单元格在图像上方大约 100 像素,在图像下方大约 100 像素。但图像大小正是我想要的。有人遇到过同样的问题吗?
因为红色空间的大小并不总是相同,而且当我在那里有一个非常大的图像时它会高很多,我相信布局认为高度应该是图像的实际高度,没有任何纵横比适合约束条件。
感谢您的帮助!
最佳答案
I want the image to be as tall as it wants, maintain the image's aspect ratio and fill the width. To do that I set the image view's constraints to be pinned to the cell's frame using auto layout and I set the image views contentMode to be Aspect Fit.
您无法仅使用自动布局来完成所有这些工作。这是因为 UIImageView
的固有内容大小就是其图像的完整大小。
相反,计算适当的高度并在设置图像时进行设置:
let imageViewWidth : CGFloat = // the width you want…
imageHeightConstraint.constant = image.size.height / image.size.width * imageViewWidth;
请注意,如果您有一个 0x0 图像,因为被零除,这将失败。如果这在您的应用中可行,请检查这种情况并将高度常量设置为 0。
此时,重新加载行,以便表格 View 重新计算高度。
关于swift - 不正确的 UITableViewCell 高度 UIImageView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30824076/