【问题标题】:Set UIImageView height proportional to width in UITableViewCell在 UITableViewCell 中设置 UIImageView 高度与宽度成比例
【发布时间】:2015-06-09 08:49:58
【问题描述】:

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

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

我设置了自动布局约束以将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.framebefore 布局已经发生,所以无论如何我都没有计算正确的高度。

我这样做是否正确?有没有一种简单的方法来设置UIImageView 的纵横比以匹配它包含的图像?提前致谢。

【问题讨论】:

  • 您是否考虑过在图像视图上使用纵横比约束?
  • 是的,成功了,谢谢。我将添加我的解决方案作为答案。

标签: ios uitableview uiimageview


【解决方案1】:

根据@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)
)

【讨论】:

  • 你将如何调用 uiviewcontroller 来刷新它的内容?比如在 uitableviewcell 上?
猜你喜欢
  • 2020-08-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-02-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-12-05
相关资源
最近更新 更多