2016-06-28 51 views
0

我有一個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! 
} 

回答

0

您不能使用的ImageView幀的寬度作爲新寬度的基礎。你需要使用一個常數值,也許是高度。

+0

常數值是寬度。我需要的寬度與單元格的寬度相同 – ttrs

0

Yup單元格被重複使用,從這個方法發佈整個代碼會很好,特別是在創建單元格的地方。

從我從中收集的是,你是否嘗試從緩存中加載圖像,如果它不存在,你從互聯網上加載它。這個解決方案的問題是,當你沒有圖像時,你會呈現一些存根圖像,並且存根長寬比。當實際圖像加載完成後,它將被放置在UIImageView內,而不調整大小。

有2種方法可以做到這一點。一個是具有恆定的圖像大小。另一種是在加載新圖像完成時重新加載單元格。

+0

謝謝您的回答,但我仍然沒有得到一件事:當所有圖像都加載並顯示在單元格中時,我開始向上和向下滑動表格。當我向上滑動時,我發現第三個單元格中的高寬比錯了,但是當我向下滑動時,相同的第三個單元格以正確的高寬比顯示圖像。所以在這種情況下,它可能不是因爲存根。 – ttrs

+0

我發佈了整個方法 – ttrs