在我的Swift应用程序中使用AlamofireImages在UITableViewCells上缓存图像

时间:2016-09-21 00:24:04

标签: ios swift uitableview alamofireimage

我正在编写一个Swift应用,用于显示我的UITableViewController的每个单元格上从服务器获取的照片。

到目前为止,我的代码如下所示:

func tableView(detailsPanel: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

    let cell = detailsPanel.dequeueReusableCellWithIdentifier("cell") as! DetailsCell

    let test:SingleTest =  self.items[indexPath.row] as! SingleTest
    if(test.photo != "") {
        cell.myPhoto.af_setImageWithURL(NSURL(string: test.photo)!)
    }

}

现在,问题是不是每个单元都有cell.photo中存储的照片。其中一些是空字符串("")。在那种情况下,当我快速滚动表格视图时,我看到那些空的UIImageView s充满了来自其他单元格的照片。

快速解决方法似乎是添加else块:

if(test.photo != "") {
    cell.myPhoto.af_setImageWithURL(NSURL(string: test.photo)!)
} //this one below:
else {
    cell.myPhoto.image = UIImage(named: "placeholderImg")
}

现在,只要没有照片,placeHolderImg就会显示在那里。但是......有没有办法避免它,只是不显示任何东西?如果不显示任何内容,我的意思是不显示来自不同单元格的图像?

1 个答案:

答案 0 :(得分:0)

您正在重复使用单元格,因此单元格仍将使用已加载的上一个图像,除非您将其设置为nil或占位符图像。但是我相信你不需要使用if语句。您可以使用af_setImageWithURL的placeholderImage参数。

cell.myPhoto.af_setImageWithURL(NSURL(string: test.photo)!, placeholderImage: image)