我有一个 UITableView,我需要在每个自定义单元格(使用 UIImageView)中显示不同的图像(具有不同的尺寸)。为了正确显示它们,我需要计算每个图像的纵横比并调整 UIImageView 的框架。但有一个问题。当我运行该应用程序时,它显示每个单元格的宽高比错误。然后我开始滑到 table 底部,然后又滑回顶部,好几次。每次我看到某些单元格的纵横比是正确的,而其他单元格的纵横比是错误的。是因为系统重用了原型(prototype)单元吗?
这是 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!
}
最佳答案
您不能使用 imageView 的框架宽度作为新宽度的基础。您需要为此使用一个常量值,例如高度。
关于ios - UITableViewCell、图像和纵横比,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38086127/