我应该怎么做才能在 tableView 中加载异步图像?

安德烈斯·戈麦斯

好吧,我应该在表格视图中加载图像,我下载并加载成功,但是当我尝试在表格视图中显示时,它们不会出现,但是,如果我在表格视图中滚动,图像会出现但是图像不会在单元格的中间。

我正在使用 swift 4.2

这行帮助我下载和加载图像

extension UIImageView {
    func downloaded(from url: URL, contentMode mode: UIView.ContentMode = .scaleAspectFit) {  
        contentMode = mode
        URLSession.shared.dataTask(with: url) { data, response, error in
            guard
                let httpURLResponse = response as? HTTPURLResponse, httpURLResponse.statusCode == 200,
                let mimeType = response?.mimeType, mimeType.hasPrefix("image"),
                let data = data, error == nil,
                let image = UIImage(data: data)
                else { return }
            DispatchQueue.main.async() {
                self.image = self.resizedImageWith(image: image, targetSize: CGSize(width: 100.0, height: 50.0))
            }
            }.resume()
    }
    func downloaded(from link: String, contentMode mode: UIView.ContentMode = .scaleAspectFit) {  
        guard let url = URL(string: link) else { return }
        downloaded(from: url, contentMode: mode)
    }
}

在我的表视图控制器中,我使用此功能下载图像

func loadImages()
    {
        for img in arrFavServices
        {
            if let url = img?.logo
            {
                let imgDownload = UIImageView()
                imgDownload.downloaded(from: url, contentMode: .redraw)
                arrImages.append(imgDownload)
            }
            else
            {
                let imgDownload = UIImageView()
                imgDownload.image = UIImage(named: "logo")
                arrImages.append(imgDownload)
            }
          tableView.reloadData()
          tableView.layoutIfNeeded()
          tableView.layoutSubviews()
          utilActivityIndicator.shared.hideLoader(view: view)
        }
    }

数组 arrFavServices 包含所有图像的 url,而 arrImages 包含先前下载的所有图像。在 viewdidload 中调用了函数 loadImages。我用这个功能来显示图像

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
        if (arrFavServices[indexPath.section]?.logo) != nil
        {
            if arrImages[indexPath.section].image != nil
            {
                cell.imageView?.image = arrImages[indexPath.section].image
                cell.imageView?.contentMode = .center
            }
        }
        // Configure the cell...
        if let color = arrFavServices[indexPath.section]?.color
        {
            cell.backgroundColor = UIColor(hexString: color)
        }
        return cell
    }

我的错误是什么?请帮助我

维卡伦

我认为你有 2 个选择

  • 当单元格可见时,您异步下载图像(我推荐)

  • 下载所有图像并显示单元格可见

如果您下载所有图像会增加应用程序的内存使用量,如果使用过多,iOS 会使您的应用程序崩溃。

第一条路径:

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
    if let logo = arrFavServices[indexPath.section]?.logo {
        // We need download image here
        cell.imageView?.downloaded(from: logo, contentMode: .center)
    }

    // Configure the cell...
    if let color = arrFavServices[indexPath.section]?.color {
        cell.backgroundColor = UIColor(hexString: color)
    }
    return cell
}

第二条路径:

您可以使用调度组。UITableView 正在等待下载所有图像。

// Cache array
var downloadedImages: [UIImage] = []

// Create an instance
var dispatchGroup = DispatchGroup()


func loadImages() {

    // Every tick of loop, we enter the group
    for img in arrFavServices {

        // Join the group
        dispatchGroup.enter()
        if let url = img?.logo {
            let imgDownload = UIImageView()
            imgDownload.downloaded(from: url, contentMode: .redraw, completion: { [weak self] downloadedImage in
                guard let self = self else { return }
                self.downloadedImages.append(downloadedImage)

                // And leave group when task is done
                dispatchGroup.leave()

            })
        } else {
            let imgDownload = UIImageView()
            imgDownload.image = UIImage(named: "logo")
            arrImages.append(imgDownload)

            // We can leave here too because we add image to array
            dispatchGroup.leave()
        }

    }

    // We have to listen group, and that we update tableView or UI todo
    dispatchGroup.notify(queue: .main) {
        self.tableView.reloadData()
        self.tableView.layoutIfNeeded()
        self.tableView.layoutSubviews()
        self.utilActivityIndicator.shared.hideLoader(view: self.view)
    }
}

您可以像下面这样设置完成处理程序

extension UIImageView {
    func downloaded(from url: URL, contentMode mode: UIView.ContentMode = .scaleAspectFit, completion: ((UIImage) -> Void)?) {
        contentMode = mode
        URLSession.shared.dataTask(with: url) { data, response, error in
            guard
                let httpURLResponse = response as? HTTPURLResponse, httpURLResponse.statusCode == 200,
                let mimeType = response?.mimeType, mimeType.hasPrefix("image"),
                let data = data, error == nil,
                let image = UIImage(data: data)
                else { return }
            DispatchQueue.main.async() {
                completion?(image)
            }
            }.resume()
    }
    func downloaded(from link: String, contentMode mode: UIView.ContentMode = .scaleAspectFit, completion: ((UIImage) -> Void)?) {
        guard let url = URL(string: link) else { return }
        downloaded(from: url, contentMode: mode, completion: completion)
    }
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

我该怎么做才能提高图像质量?

在TableView中异步加载图像

如果我尝试更改图像的宽度和高度,图像尺寸会增加。我应该怎么做才能获得缩小尺寸的图像?

我的图像在图像滑块上看起来很糟糕-应该怎么做才能使图像看起来不被拉伸?

我需要怎么做才能使用Meteor加载引导示例

我应该怎么做才能在游戏中获得更好的FPS

我应该怎么做才能在Java中使用ELement类

我应该怎么做才能在WebStorm的.ts文件中解析“角度”

我应该怎么做才能在 Octave 上绘制小波?

我应该怎么做才能在 django rest 框架中的代码中发布多个内容?

我应该怎么做才能在WebAPI中返回一对多列表?

我应该怎么做才能在php中获得像这样的数组?

我应该怎么做才能优化我的慢跑性能?

我应该怎么做才能在启动时强制检查根文件系统(以及可选的修复程序)?

我想渲染图像的数量,图像应该在 React Native 中随机播放吗?怎么做?谁能帮我

如果图像在延迟加载图像加载后损坏,则设置图像默认值。我怎么做?

如果有条件地执行Task,异步方法应该怎么做?

我只能以root身份执行口径(使用sudo)。我应该怎么做才能在没有root特权的情况下执行它?

我应该怎么做才能使用 express-jwt 访问我的静态资源?

我应该怎么做才能使我的容器使用范围?

我应该怎么做才能让我的盒子水平对齐?

我该怎么做才能在Heroku上使用python-magic?

我应该怎么做才能在这款Toshiba笔记本电脑上使用Windows 10进行Ubuntu双重引导?

我应该怎么做才能找到指向Confluence用户家的超链接?

我应该怎么做才能避免服务层方法中的代码重复?

我应该怎么做才能解决这个 cv2 错误?

我应该怎么做才能看到静态和动态绑定在起作用?[C ++]

我应该怎么做才能最大程度地利用Nvidia GeForce FX 5500显卡?

我应该怎么做才能发布 React Native Expo App?