我正在尝试制作一个 UITableView
,其中每个单元格包含纵向或横向 UIImageView
,其中图像在填充屏幕宽度时保持其纵横比,如下所示:
| |
|########|
|########|
|########|
|########|
|########|
| |
|########|
|########|
|########|
| |
我已经设置了autolayout约束来附加 UIImageView
's edges to the table view cell' s contentView
. 这适用于宽度,但高度不是我想要的 - 它总是扩展到底层图像的整个高度 .
我在表视图上有这些设置:
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
这里的问题是我得到的是在布局发生之前,所以无论如何我都没有计算出正确的高度 .
我是以正确的方式来做这件事的吗?有没有一种简单的方法来设置 UIImageView
的宽高比以匹配它包含的图像?提前致谢 .
1 回答
根据@ Wain的建议,添加宽高比约束解决了这个问题: