繁体   English   中英

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

[英]Set UIImageView height proportional to width in UITableViewCell

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

|        |
|########|
|########|
|########|
|########|
|########|
|        |
|########|
|########|
|########|
|        |

我已经设置了autolayout约束来将UIImageView的边缘附加到表视图单元格的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

这里的问题是我得到的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)
)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM