![](/img/trans.png)
[英]Aspect ratio NSLayoutConstraint in UITableViewCell is breaks
[英]UITableViewCell, images and aspect ratio
我有一個UITableView,我需要在每個自定義單元格(帶有UIImageView)中顯示不同的圖像(具有不同的大小)。 為了正確顯示它們,我需要計算每個圖像的長寬比並調整UIImageView的框架。 但有一個問題。 當我運行該應用程序時,它會為每個單元格顯示錯誤的寬高比。 然后,我開始滑到桌子的底部,然后再回到頂部,幾次。 每次我看到正確的長寬比,對於某些單元格,對於其他單元格,則錯了。 是因為系統正在重用原型單元嗎?
這是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框架的寬度用作新寬度的基礎。 您需要為此使用一個恆定值,也許是高度。
Yup單元被重用,最好將這種方法的整個代碼發布出來,尤其是在創建單元的地方。
根據我的收集,是您嘗試從緩存加載圖像,如果不存在,則從Internet加載圖像。 此解決方案的問題是,當您沒有圖像時,您將以存根的長寬比顯示一些存根圖像。 實際圖像加載完成后,將直接放置在UIImageView
,而無需調整大小。
有兩種方法可以做到這一點。 一種是具有恆定的圖像尺寸。 另一種是在新圖像加載完成后重新加載單元。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.