ios - 在 UITableViewCell 中设置与宽度成比例的 UIImageView 高度

标签 ios uitableview uiimageview

我正在尝试创建一个 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/

相关文章:

ios - 相册像表 iOS

ios - UIImageView 触摸点

ios - UITableView 以编程方式在 UIScrollView 内部不调用委托(delegate)方法

ios - 新的 CoreData 版本属性未显示

iphone - 使用对象按字母顺序对 tableview 进行排序并显示按字母顺序排列的 tableview 标题,如通讯录

ios - 图像在屏幕上水平滑动时循环播放,看起来像是在无限滚动

ios - AudioConverterRef 采样率转换 (iOS)

ios - Swift:UIImages 在表格 View 中出现乱序

ios - 使用 VoiceOver 在多个 UITableView 之间切换会导致崩溃

ios - Swift 3 更新错误 - 在展开可选值时意外发现 nil