如何刷新 UITableViewCell 中的 UIImage?

How to refresh an UIImage in an UITableViewCell?

这就是我创建细胞的方式:

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

        let cell = tableView.dequeueReusableCellWithIdentifier("FbFriendCell") as! FbFriendCell
        cell.initialize()
        return cell  
}

很简单。

在 initialize() 函数中,我下载了一张图片并将其放入 UIImageView 中:

let theImageView = UIImageView(image: userPhoto)
theImageView.frame = CGRect(x: 0, y: 0, width: 80, height: 80)
self.addSubview(theImageView)
theImageView.image = userPhoto
println("The image has been set !")

问题是图像只在这条日志消息后几秒出现:

println("The image has been set !")

如何强制重新加载图像?

* 阅读 * => 这个问题可能与图像在 UITableViewCell 中的事实密切相关!

确保更新主队列中的图像

 dispatch_async(dispatch_get_main_queue(), { () -> Void in
            //Update UI
 })

我以前遇到过这个问题,这解决了我的problem.Just尝试

我认为您下载图像是异步的。当程序到达 println("The image has been set !") 行时会出现您的日志,但实际上您的图像尚未下载。您应该将日志移到下载回调的末尾,然后日志应该在图像出现时及时出现。

或者,这可能是因为您没有在 UI 线程中更新 UIImageView。你可以这样做:

dispatch_async(dispatch_get_main_queue(), { () -> Void in
        //Set image to UIImageView
})

在 Swift3 中有一种更好的方法来访问 UI 线程。

DispatchQueue.main.async() {

}

有人说这比dispatch_async慢,但我在实际使用中从未发现有什么不同。