为了实现这一点,我先用一本字典[Int:CGFloat]
保持细胞的计算heigths然后在heightForRowAtIndexpath
方法用在你的字典里依然古色古香的值,在你的cellForRowAtIndexpath
方法,你应该下载你的图像,计算纵横比,乘以你的单元宽度或通过您的宽高比的图像的宽度和放入相应IndexPath数中计算出的高度中的字典
在代码这样的事情,这是使用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()
}
}
})
}
我希望这一点帮助
您可以将图像宽度和高度发送到服务器,然后在返回时可以相应地为图像指定单元格宽度和高度。 –