我正在尝试创建一个 UITableView
,其中每个单元格包含纵向或横向 UIImageView
,其中图像在填充屏幕宽度的同时保持纵横比,像这样:
| |
|########|
|########|
|########|
|########|
|########|
| |
|########|
|########|
|########|
| |
我设置了自动布局约束以将 UIImageView
的边缘附加到表格 View 单元格的 contentView
。这适用于宽度,但高度不是我想要的 - 它总是扩展到底层图像的整个高度。
我在表格 View 上有这些设置:
self.tableView.estimatedRowHeight = 100.0;
self.tableView.rowHeight = UITableViewAutomaticDimension;
构建单元格时,我试图计算必要的高度,以便我可以更改 UIImageView
的框架(或高度限制):
let cell = tableView.dequeueReusableCellWithIdentifier("activityPostCell", forIndexPath: indexPath) as UITableViewCell
let image = UIImage(named: "my-image.jpg")
let aspectRatio = image!.size.height / image!.size.width
let imageView = cell.viewWithTag(15) as UIImageView
let imageViewHeight = aspectRatio * imageView.frame.width
这里的问题是我得到的 imageView.frame
是在布局发生之前,所以无论如何我都没有计算正确的高度。
我的做法是否正确?有没有一种简单的方法来设置 UIImageView
的纵横比以匹配它包含的图像?提前致谢。
最佳答案
按照@Wain 的建议,添加纵横比约束解决了问题:
let image = UIImage(named: "my-image.jpg")
let aspectRatio = image!.size.height / image!.size.width
let imageView = cell.viewWithTag(15) as UIImageView
imageView.addConstraint(NSLayoutConstraint(
item: imageView,
attribute: NSLayoutAttribute.Height,
relatedBy: NSLayoutRelation.Equal,
toItem: imageView,
attribute: NSLayoutAttribute.Width,
multiplier: aspectRatio,
constant: 0)
)
关于ios - 在 UITableViewCell 中设置与宽度成比例的 UIImageView 高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29446155/