Swift – 基于图像宽高比的dynamicUITableViewCell大小

我试图创builddynamic大小的UITableViewCells,根据从服务器下载的图像的纵横比来改变高度。

例如,如果图像的高度是其宽度的两倍,那么我希望UITableViewCell的高度是屏幕宽度的两倍,这样图像可以占据屏幕的整个宽度并保持高宽比。

我试图做的是将约束添加到单元格,并使用UITableViewAutomaticDimension来计算高度,但我面临的问题是,我不知道图像的长宽比,直到下载,因此单元格开始小,然后一旦tableView手动刷新单元格显示正确的大小。

我不想重新加载每个单独的单元格时,它的图像下载是一个伟大的方式来做事情。

这种方法是最好的方法吗? 我不能为了我的生活而思考如何做到这一点,因为当初始化时,我不知道单元内部的宽高比。

为了达到这个目的,我首先使用一个字典[Int:CGFloat]来保留单元格的计算高度,然后在heightForRowAtIndexpath方法中使用保存在你的字典中的值,在你的cellForRowAtIndexpath方法中,你应该下载你的图像,计算宽高比,乘以单元格宽度或您的图像宽度由您的长宽比,并把相应的索引号码计算在您的字典中的高度

在这样的代码中,这是使用alamofire加载图像的代码示例

  var rowHeights:[Int:CGFloat] = [:] //declaration of Dictionary //My heightForRowAtIndexPath method func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { if let height = self.rowHeights[indexPath.row]{ return height }else{ return defaultHeight } } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { if let cell = tableView.dequeueReusableCell(withIdentifier: "ImageCell") as? ImageCell { let urlImage = Foundation.URL(string: "http://imageurl") cell.articleImage.af_setImage(withURL: urlImage, placeholderImage: self.placeholderImage, filter: nil, imageTransition: .crossDissolve(0.3), completion: { (response) in if let image = response.result.value{ DispatchQueue.main.async { let aspectRatio = (image! as UIImage).size.height/(image! as UIImage).size.width cell.articleImage.image = image let imageHeight = self.view.frame.width*aspectRatio tableView.beginUpdates() self.rowHeights[indexPath.row] = imageHeight tableView.endUpdates() } } }) } 

我希望这有帮助