我有一個UITableView,我需要在每個自定義單元格(使用UIImageView)中顯示不同的圖像(具有不同的大小)。爲了正確顯示它們,我需要計算每個圖像的寬高比並調整UIImageView的框架。但有一個問題。當我運行該應用程序時,它顯示每個單元格的錯誤寬高比。然後我開始滑到桌子的底部,再次回到頂部,幾次。每次我看到正確的縱橫比,對於某些細胞,對於其他細胞都是錯誤的。是因爲系統重複使用原型單元嗎?UITableViewCell,圖像和長寬比
這裏是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!
}
常數值是寬度。我需要的寬度與單元格的寬度相同 – ttrs