简体   繁体   English

如何调整UIImageView的大小并强制父UITableViewCell的重新布局

[英]How to resize a UIImageView and force relayout of the parent UITableViewCell

I have custom TableViewCells that have UITableViewAutomaticDimension. 我有具有UITableViewAutomaticDimension的自定义TableViewCells。 When I load an image into the cell, it's almost always much too tall for the image, and I end up with large white bars above and below the image. 当我将图像加载到单元格中时,对于该图像而言,它几乎总是太高了,最终在图像的上方和下方都有大的白条。 What I am attempting to do is resize the UIImageView to be the same size as the image, but nothing will work. 我正在尝试做的是将UIImageView调整为与图像相同的大小,但是没有任何效果。

I also tried creating a new UIImageView and setting that up, but UIImageView.init(frame: CGRectMake(...) ) returns nil for some reason. 我也尝试创建一个新的UIImageView并进行设置,但是UIImageView.init(frame: CGRectMake(...) )由于某些原因返回nil My Google-fu is failing me on this one. 我的Google-fu在这方面使我失败。

My code for (attempting) to resize the imageView and parent cell: (note that i is my new image and cell.postImage is an IBOutlet of type UIImageView! ) 我的代码(尝试)以调整imageView和父单元的大小:(请注意, i是我的新图像, cell.postImageUIImageView!类型的IBOutlet UIImageView!

let oFrame = cell.postImage.frame
let width = oFrame.width
let height = (i.size.height / i.size.width) * width
cell.postImage.frame = CGRectMake(oFrame.origin.x, oFrame.origin.y, width, height)
cell.postImage.contentMode = .ScaleAspectFit
cell.postImage.image = i
cell.setNeedsUpdateConstraints()
cell.setNeedsLayout()
cell.layoutIfNeeded()

Set the width constraint for postImage. 设置postImage的宽度约束。 Create an IBOutlet for the height constraint of postImage. 为postImage的高度约束创建一个IBOutlet。 Then in say something like: 然后说类似:

let oFrame = cell.postImage.frame
let width = oFrame.width
let height = (i.size.height / i.size.width) * width
cell.postImageHeightConstraint.constant = height

And it looks like you want the image center so align center x. 看起来您想要图像中心,所以将中心x对齐。

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

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