在UITableViewCell中将UIImageView高度设置为与宽度成比例

Mic*_*ael 5 uitableview uiimageview ios

我正在尝试制作UITableView每个单元格包含纵向或横向的位置UIImageView,其中图像在填充屏幕宽度时保持纵横比,如下所示:

|        |
|########|
|########|
|########|
|########|
|########|
|        |
|########|
|########|
|########|
|        |
Run Code Online (Sandbox Code Playgroud)

我已设置自动布局约束以将UIImageView边缘附加到表格视图单元格contentView.这适用于宽度,但高度不是我想要的 - 它总是扩展到底层图像的整个高度.

我在表视图上有这些设置:

self.tableView.estimatedRowHeight = 100.0;
self.tableView.rowHeight = UITableViewAutomaticDimension;
Run Code Online (Sandbox Code Playgroud)

在构造单元格时,我正在尝试计算必要的高度,以便我可以更改以下框架(或高度约束)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
Run Code Online (Sandbox Code Playgroud)

这里的问题是imageView.frame我得到的是布局发生之前,所以我还是没有计算出正确的高度.

我是以正确的方式来做这件事的吗?有没有一种简单的方法来设置UIImageView宽高比以匹配它包含的图像?提前致谢.

Mic*_*ael 7

根据@ 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)
)
Run Code Online (Sandbox Code Playgroud)