在启动时自动加载图像Swift tableview

时间:2018-04-30 11:51:18

标签: ios swift

我有一个超级小问题...我已经完成了一个RSS提要应用程序并且在打开时我有所有文章的列表但是图像没有加载,直到我开始滚动提要。

我用来下载图片并将它们附加到tableview的每个单元格的代码如下:

let task = URLSession.shared.dataTask(with: url!) { data, response, error in
            guard let data = data, error == nil else { return }

            DispatchQueue.main.async() {
                // execute on main thread
                cell.imageView?.image = UIImage(data: data, scale: 12)
                //cell.imageView?.image = UIImage(data: data)
            }
        }

        task.resume()

我将此代码插入:

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

提前谢谢你。

修改

我找到了一个可能的解决方案但是当我实现它时,应用程序变得有点慢:

if let data = NSData(contentsOf: url!){
            cell.imageView?.image = UIImage(data: data as Data, scale: 12)
        }

3 个答案:

答案 0 :(得分:0)

使用SDWebImage库并将其导入您的课程

cell.yourImageView!.sd_setImage(with: yourImageURL, placeholderImage: UIImage(named: "placeHolderImageName") , options: .continueInBackground, completed: nil)

它将下载并自动将图像加载到表格单元格中。您可以在下载图像时给出一个虚拟的placeHolder图像放置在imageView中。

答案 1 :(得分:-1)

请详细说明cellForRowAt数据源方法。 此方法仅在显示视图时调用。此时图像将下载。

我建议您使用SDWebImage缓存库,下载后不会下载图像。

答案 2 :(得分:-1)

You can use this line  guard let cell = tableView.cellForRow(at: indexPath) else { return } as follow.

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell")
        let task = URLSession.shared.dataTask(with: url!) { data, response, error in
                guard let data = data, error == nil else { return }


                DispatchQueue.main.async() {
guard let cell = tableView.cellForRow(at: indexPath) else { return }
                    // execute on main thread
                    cell.imageView?.image = UIImage(data: data, scale: 12)
                    //cell.imageView?.image = UIImage(data: data)
                }
            }

            task.resume()

        }

The purpose of the line is to check if the cell is visible on the screen or not. If visible in that case it will plot the image on the cell's image view else guard statement return from the .cellForRow(IndexPath)