I have a UITableView and I need to show different images (with different sizes) in each custom cell (with UIImageView). In order to display them properly I need to calculate aspect ratio of each image and adjust UIImageView's frame. But there is a problem. When I run the app, it displays wrong aspect ratio for every cell. Then I start sliding to the bottom of the table, and back to the top again, several times. And each time I see right aspect ratio, for some cells, and wrong for others. Is it because the system is reusing the prototype cell?
Here is the code in tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath)
:
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("EntryCell", forIndexPath: indexPath) as? PodCell
let podcast = podList[indexPath.row]
let title = podcast.title
// cell.titleLa?.text = title
cell?.titleLabel.lineBreakMode = .ByWordWrapping
cell?.titleLabel.numberOfLines = 0
cell?.titleLabel.text = title
var image = UIImage()
if (imageCache[podcast.imageURL!] != nil) {
image = imageCache[podcast.imageURL!]!
cell?.imgView.image = image
}else{
let imgURL = NSURL(string: podcast.imageURL!)
let request = NSURLRequest(URL: imgURL!)
let config = NSURLSessionConfiguration.defaultSessionConfiguration()
let session = NSURLSession(configuration: config)
let task = session.dataTaskWithRequest(request) { (data: NSData?, response: NSURLResponse?, error:NSError?) in
if error == nil {
if data != nil {
image = UIImage(data: data!)!
}
dispatch_async(dispatch_get_main_queue(), {
self.imageCache[podcast.imageURL!] = image
cell?.imgView.image = image
})
}else {
print(error)
}
}
task.resume()
}
let aspectRatio = image.size.width / image.size.height
cell?.imgView.frame = CGRectMake((cell?.imgView.frame.origin.x)!, (cell?.imgView.frame.origin.y)!, (cell?.imgView.frame.width)!, (cell?.imgView.frame.width)! / aspectRatio)
return cell!
}