【问题标题】:caching images on UITableViewCells with AlamofireImages in my Swift app在我的 Swift 应用程序中使用 AlamofireImages 在 UITableViewCells 上缓存图像
【发布时间】:2016-09-21 00:24:04
【问题描述】:

我正在编写一个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 中。其中一些是空字符串 ("")。在那种情况下,当我快速滚动表格视图时,我看到那些空的UIImageViews 充满了来自其他单元格的照片。

对此的快速修复似乎是添加一个else 块:

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

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

【问题讨论】:

    标签: ios swift uitableview alamofireimage


    【解决方案1】:

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

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

    【讨论】:

    • 你能告诉我如何将它设置为 nil 吗?我尝试在else 语句中写入:cell.myPhoto = nil 但是当我滚动列表时出现错误fatal error: unexpectedly found nil while unwrapping an Optional value
    猜你喜欢
    • 1970-01-01
    • 2017-09-25
    • 1970-01-01
    • 1970-01-01
    • 2017-12-21
    • 1970-01-01
    • 2015-10-31
    • 1970-01-01
    • 2012-07-15
    相关资源
    最近更新 更多