I\'m trying to create dynamically sized UITableViewCells, changing the height based on the aspect ratio of an image downloaded from a server.
For example, if an imag
For achieve this I use first a dictionary [Int:CGFloat]
to keep the calculated heigths of cells then in the heightForRowAtIndexpath
method use the values keeped in your dictionary, in your cellForRowAtIndexpath
method you should download your image, calculate the aspect ratio, multiply your cell width or your image width by your aspect ratio and put the height calculated in correspondent IndexPath number in your dictionary
In code something like this, this is an example of code using alamofire to load the images
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()
}
}
})
}
I hope this helps