爲了實現這一點,我先用一本字典[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()
}
}
})
}
我希望這一點幫助
您可以將圖像寬度和高度發送到服務器,然後在返回時可以相應地爲圖像指定單元格寬度和高度。 –