ios - 带有 UITableView 单元格的 Swift 4 AlamofireImage

标签 ios swift uitableview alamofire alamofireimage

我正在使用 AlamofireImages 尝试从服务器下载图像并将其显示在我的表格 View 单元格中,这就是我得到的,但我的图像没有出现,只有 textLabel 和 detailTextLabel

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        let cell = tableView.dequeueReusableCell(withIdentifier: "trendingCell", for: indexPath)

        print(self.array[indexPath.row])

        cell.textLabel?.text = (self.array[indexPath.row]["title"] as! String)

        cell.detailTextLabel?.text = (self.array[indexPath.row]["username"] as! String)

        Alamofire.request("http://xxxxxxx.com/uploads/" + (self.array[indexPath.row]["cover"] as! String)).responseImage { response in
            if let image = response.result.value {
                cell.imageView?.image = image
            }
        }

        return cell
    }

最佳答案

当然,您的图片不会为您显示。因为当 Alamofire 开始下载您的图像时,它会在后台线程中进行处理。但是你在主线程或 UI 线程中工作,所以你需要从后台切换到主线程,它会为你工作。

Alamofire.request("http://xxxxxxx.com/uploads/" + (self.array[indexPath.row]["cover"] as! String)).responseImage { response in
       DispatchQueue.main.async {
            if let image = response.result.value {
                cell.imageView?.image = image
            }
        }
}

如果您认为这样做有困难,我建议您使用这个名为 Kingfisher 的库,它会为您处理异步加载图像,使您的单元格表格顺利运行。

链接:https://github.com/onevcat/Kingfisher

关于ios - 带有 UITableView 单元格的 Swift 4 AlamofireImage,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50440980/

相关文章:

ios - UITableViewCell 缩进仅适用于默认单元格 textLabel

iOS 推送通知 - 角标(Badge)不会显示

基于 iPhone 室内位置的应用程序

swift - 为什么 Swift 访问修饰符默认不是私有(private)的?

ios - UITableViewCell imageview 滚动时消失

ios - 找不到“UIKit/UIUserActivity.h”文件,Xcode 9.4

ios - 使用 SpriteKit 删除 if 语句中的 Sprite

ios - Swift 中的闭包,Objective-C 中的 block : their usefulness and when to use

iOS 7 UITableView 默认分隔符在重新排序后变得奇怪

ios - UITableView didSelectRowAt 无法获取我的单元格